还有另一种方法可以使用 Rxjs 框架调用每个组件的数据,确保服务对所有组件都是可重用的,所以你可以在服务中编写代码并仅在组件中订阅:
服务
import { Injectable } from 'angular2/core';
import { Http } from 'angular2/http';
import { Result} from './models/result'; // model imported
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class Service {
private _result: Result[];
constructor(private http: Http) {
this.result$ = new BehaviorSubject<Result[]>(this._result)
}
result$: BehaviorSubject<Result[]>;
private _urlGet = '/api';
getPlacesForUser(): void{
this.http.get(this._urlGet)
.map(res => JSON.parse(res.text()))
.catch(error => console.log(error))
.subscribe(result => {
this.result = result;
})
}
}
零件
constructor(private _service: Service)
ngOnInit(): any {
this._service.result$.map(result => result.filter(res =>
res.id)).subscribe(
result => this.result = result); // map is optional to filter json
}