3

希望有人可以为我澄清一些事情。我现在正在做什么,使用 Angular 1.4.6:

我创建一个服务

'use strict';
angular.module('App')
.factory('processingService', ['$http',
    function ($http) {
        var settings = 'Settings/GetSettings';    
        var getSettings = function()
        {
            return $http.get(settings)
                .then(function(response)
                {
                    return response.data;
                });
        };
        return {
            getSettings: getSettings           
        };
    }
]);

并在我的控制器中使用/注入它。

'use strict';
angular.module('App')
.controller('appController', [
    '$scope','appService',
    function ($scope, appService) {     
        var onSettings = function (data) {
            if (data.hasOwnProperty('Settings')) {    
                //Code handling Settings          
            }
        };
        var onSettingsError = function()
        {
           //Handle Errors
           $scope.showLoader = false;
        };      
        appService.getSettings()
            .then(onSettings, onSettingsError);
}]);

我开始玩 angular2 beta 并在 http.get 上找到了以下示例

getRandomQuote() {
  this.http.get('http://localhost:3001/api/random-quote')
    .map(res => res.text())
    .subscribe(
      data => this.randomQuote = data,
      err => this.logError(err),
      () => console.log('Random Quote Complete')
    );
}

logError(err) {
  console.error('There was an error: ' + err);
}

我构建了一些其他方法并进行了一些测试并进行了很多搜索,但在使用 angular2 beta 和 typescript 创建服务时找不到任何类似的东西,就像我到目前为止所做的那样。是否有必要这样做。或者这不是现在使用 Angular2 beta 的方式吗?

先感谢您。

4

2 回答 2

2

http.get您可以简单地从您的服务中返回一个可观察对象(方法返回的内容),即带有Injectable注释的类:

@Injectable()
export class CompanyService {
  constructor(http:Http) {
    this.http = http;
  }

  getRandomQuote() {
    return this.http.get('http://localhost:3001/api/random-quote')
                  .map(res => res.json());
  }
}

在您的组件中,您可以注入此服务并调用实际执行 HTTP 请求的方法。要获得结果,只需使用以下subscribe方法:

export class CompanyList implements OnInit {
  public companies: Company[];

  constructor(private service: CompanyService) {
    this.service = service;
  }

  logError(err) {
  }

  ngOnInit() {
    this.service.getRandomQuote().subscribe(
      data => this.randomQuote = data,
      err => this.logError(err),
      () => console.log('Random Quote Complete')
    );
  }
}

您可以在此地址获得更多详细信息:如何在 Angular 2 beta 的服务中有效地使用 Http 组件?.

希望它会帮助你,蒂埃里

于 2015-12-29T15:55:31.917 回答
0

Angular 2 中的服务只是用@Injectable()修饰的 TypeScript 类。

该服务可能如下所示:

import {Injectable, Inject, EventEmitter} from 'angular2/core';
import {Http, Response} from 'angular2/http';

@Injectable() // annotated class that can be injected in other components
export class ProcessingService {
  // inject the http service (configured in the global injector)
  constructor(@Inject(Http) private http :Http) {

  }
  // the service method returning an event emmiter (instead of promises)
  public getSettings():EventEmitter<string> {

      let emmiter = new EventEmitter<string>(true);

      // call the method and subscribe to the event emmiter
      this.http.get('Settings/GetSettings').subscribe((value: Response) => {
        emmiter.emit('called');    
      });
      return emmiter;
  }
}

然后您可以使用依赖注入将服务插入到组件中,如下所示:

import {Component, Inject } from 'angular2/core';
// import our service
import {ProcessingService} from './services/processing-service/processing-service';

@Component({
  selector: 'http-search-params-app',
  providers: [],
  templateUrl: 'app/http-search-params.html',
  pipes: [],
  bindings:[ProcessingService] // tell the component injector to inject our service
})
export class HttpWorkApp {
  workDone = [];

  constructor(private processingService: ProcessingService) {}

  // call the sevice 
  public doWork() {
      this.processingService.getSettings().subscribe((value :string) =>{
          this.workDone.push(value);
      });
  }
}

该组件的模板:

<div>
    <button (click)="doWork()">Call HTTP Service</button>
    <div *ngFor="#workItem of workDone">{{workItem}}</div>    
</div>

您还需要配置全局注入以允许注入Http服务。

import {bootstrap} from 'angular2/platform/browser';
import {HttpWorkApp} from './app/http-search-params';
import {HTTP_PROVIDERS} from 'angular2/http';

bootstrap(HttpWorkApp, [HTTP_PROVIDERS]);
于 2015-12-29T14:53:14.413 回答