我对angular2很新,我有点卡在某事上.
我创建了一个全局settings.service.此服务从API获取设置,并使用收集的数据填充设置模型.
服务:
public settings : settingsModel; constructor(public http: Http){ this.setSettings() .subscribe( (data) => { this.settings = data }); } setSettings() : Observable<any>{ return : this.http.get('/settings') .map(response => response.json()); } getSettings(){ return this.settings; }
这工作正常,我在.map中测试返回数据时正确设置了设置
但是当我尝试从需要此数据的组件调用GetSettings时,它返回空.该服务在引导程序中定义.
我是否需要使’settings’变量可观察?任何帮助将非常感谢!
TNX!
我将使用do运算符将缓存实现到您的服务中:
private settings : settingsModel; constructor(public http: Http){ this.settingsObservable = this.http.get('/settings') .map(response => response.json()) .do(settings => { this.settings = settings; }).share(); } getSettings() { if (this.settings) { return Observable.of(this.settings); } else { return this.settingsObservable; } }