Angular 2可以实现服务。它们仅对应于如下所述的可注射类。在这种情况下,此类可以注入到其他元素(如组件)中。
import {Injectable} from 'angular2/core';import {Http, Headers} from 'angular2/http';import 'rxjs/add/operator/map';@Injectable()export class CompanyService { constructor(http:Http) { this.http = http; }}您可以在引导应用程序的主要组件时
Http指定的条件下(使用其构造函数)在其中注入对象
HTTP_PROVIDERS:
import {bootstrap} from 'angular2/platform/browser'import {HTTP_PROVIDERS} from 'angular2/http';import {AppComponent} from './app.component'bootstrap(AppComponent, [ HTTP_PROVIDERS]);然后可以将该服务注入到组件中,如下所述。不要忘记
providers在组件列表中指定它。
import { Component, View, Inject } from 'angular2/core';import { CompanyService } from './company-service';@Component({ selector: 'company-list', providers: [ CompanyService ], template: ` (...) `})export class CompanyList { constructor(private service: CompanyService) { this.service = service; }}然后,您可以实现一种利用
Http服务中的对象的方法,并返回与您的请求相对应的Observable对象:
@Injectable()export class CompanyService { constructor(http:Http) { this.http = http; } getCompanies() { return this.http.get('https://angular2.apispark.net/v1/companies/') .map(res => res.json()); }}然后,组件可以调用此
getCompanies方法,并在Observable对象上预订回调,以便在响应存在时通知以更新组件的状态(与在Angular1中对promise所做的方式相同):
export class CompanyList implements onInit { public companies: Company[]; constructor(private service: CompanyService) { this.service = service; } ngonInit() { this.service.getCompanies().subscribe( data => this.companies = data); }}编辑
正如foxx在他的评论中建议的那样,
async管道还可以用于隐式订阅可观察对象。这是使用它的方法。首先更新您的组件,以将可观察对象放入您要显示的属性中:
export class CompanyList implements onInit { public companies: Company[]; constructor(private service: CompanyService) { this.service = service; } ngonInit() { this.companies = this.service.getCompanies(); }}然后在模板中使用异步管道:
@Component({ selector: 'company-list', providers: [ CompanyService ], template: ` <ul> <li *ngFor="#company of companies | async">{{company.name}}</li> </ul> `})export class CompanyList implements onInit { (...)}


