2017-10-04 31 views
0

我有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 (

回答

0

的問題是你的地圖功能要覆蓋_docData到響應對象(即數組類型)沒有觀察到裏面。而且它沒有下一個功能。

試試下面這個

_docdata: BehaviorSubject<DetailSection[]>; 

service.getData(){return this.http.get(this.url) 
     .map((res) =>{ 
      let detailSections = res.json(); 
      this._docdata = new BehaviorSubject<DetailSection[]>(detailSections); 
      console.log("1st return"); 
      return detailSections; })  
      .catch((error:any) => Observable.throw(error|| 'Server error')); } 
+0

感謝您的回覆。 但我得到錯誤的_docdata.next()在刷新()方法 錯誤=>錯誤類型錯誤:_this._docdata.next不是一個函數 – aabbcc

+0

是你刷新錯誤的原因,因爲在你初始化的getData _docData不包含BehaviourSubject的對象。你有沒有嘗試上面的代碼? –

+0

現在刷新()工作正常。但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

0

的代碼工作對我罰款。

  • 主題變量

    _docdata:BehaviorSubject =新BehaviorSubject([]); 012ddocdata:Observable = this._docdata.asObservable();

    的getData()/刷新(){返回this.http.get(this.url) .MAP(RES => res.json()) .subscribe((數據:DetailSection [])=> { this._docdata.next(data); console.log(this._docdata)}, (err:any)=> console.error(「fetch:ERROR」,err), ()=> console.log(「取:總是「));}

  • 取出在組件作爲響應:

    this.detailService.getPageData(鍵,srcFrom); (dataList)=> {this.dataList = dataList; console.log(「dataList from component」,this.dataList);});