[英]Angular2 global variable observable
我對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!
在您的服務中使用BehaviorSubject 。 它已經共享,它將為新訂閱者提供當前值(因此它為您進行緩存):
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {settingsModel} from 'settingsModel';
@Injectable()
export class MyService {
private _settingsSource = new BehaviorSubject<settingsModel>(null);
settings$ = this._settingsSource.asObservable();
constructor(private _http:Http) {
this._http.get('./settings.json')
.subscribe(response => {
//console.log('response', response)
this._settingsSource.next(response.json())
});
}
}
然后使用模板中的observable和asyncPipe,或者將數據提取到組件變量中:
this.settings$ = this._myService.settings$; // use with asyncPipe
this._myService.settings$.subscribe(data => this.settings = data);
在Plunker中我有一個等待4秒的子組件然后subscribe()
s,以顯示確實檢索到最新/當前值。 Plunker還演示了asyncPipe的使用。
我將使用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;
}
}
為什么不使用這樣的服務: -
public settings : settingsModel;
constructor(public http: Http){ }
GetSettings(){
return this.http.get('/settings')
.map(response => {
this.settings = response.json() // here setting your data to `this.setting`
return this.settings;
})
.catch(err => {
console.log(err) // handle your error as you want to handle
})
}
然后使用.subscribe()
方法來獲取數據並在視圖上顯示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.