2017-10-04 28 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);});