Angular 2 HTTP GET 等同于 Angular HTTP GET

Angular 2 HTTP GET Equivalent to Angular HTTP GET

希望有人能为我澄清一些事情。 我现在正在做什么,使用 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/inject 在我的控制器中。

'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 和打字稿创建服务时找不到任何类似的东西,就像我到目前为止所做的那样。 甚至有必要那样做吗? 或者这不是现在使用 Angular2 beta 的方式吗?

提前致谢。

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]);

您可以从您的服务中简单地 return 一个可观察对象(http.get 方法 returns),即 class 和 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')
    );
  }
}

您可以在此地址获得更多详细信息:

希望对您有所帮助, 蒂埃里