我有2個兄弟組件有一個服務,它具有HTTP調用來渲染一個json。 OnInit,組件B獲取調用服務的HTTP響應並加載屏幕。 組件A上的click事件應使組件B刷新其數據。在AngularJS的BehaviourSubject中的HTTP響應緩存和nexting 2/4
我跟着從張貼ObjectiveTC了答案 - >What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?
_docdata: BehaviorSubject<DetailSection[]> = new BehaviorSubject<DetailSection[]>([]);
service.getData(){return this.http.get(this.url)
.map((res) =>{this._docdata = (res.json()); console.log("1st return"); return this._docdata; })
.catch((error:any) => Observable.throw(error|| 'Server error')); }
這工作得很好。
refresh(){
this.http.get("../../assets/reqd-detail.json")
.map(res => res.json())
.subscribe((data:Array<DetailSection>) => this._docdata.next(data));
}
getting error --> ERROR TypeError: _this._docdata.next is not a function at SafeSubscriber._next (detail.service.ts:156) at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238) at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185) at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125) at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (
感謝您的回覆。 但我得到錯誤的_docdata.next()在刷新()方法 錯誤=>錯誤類型錯誤:_this._docdata.next不是一個函數 – aabbcc
是你刷新錯誤的原因,因爲在你初始化的getData _docData不包含BehaviourSubject的對象。你有沒有嘗試上面的代碼? –
現在刷新()工作正常。但getData()不呈現響應。 刷新(){ 返回this.http.get( 「../../資產/ REQD-detail.json」)\t \t \t .MAP \t(RES => res.json()) \t \t .subscribe((data:DetailSection [])=> {this._docdata.next(data); console.log(this._docdata)}, \t \t(err:any)=> console.error(「fetch:ERROR 「),err), \t \t()=> console.log(」fetch:always「)); } – aabbcc