Observable Undefined

旧巷老猫 提交于 2019-12-18 07:15:21

问题


I'm trying to extract the values from an observable, my subscription (component) code is as followed:

this.checkoutService.getDisabledDate().subscribe
(dates=>{this.formattedDate=dates}, 
(error:any)=>{console.log(error)});

In the 'dates' callback a console.log of this.formattedDate prints the correct values. However trying to access this.formattedDate outside of the subscription is undefined.

the service code:

getDisabledDate():Observable<any>{
    let headers = new Headers({'Content-Type': 'application/json' });
    let options = new RequestOptions({headers:headers});
    let userRequest={action_id:0};
    let disabledDate={};

    return this.http
        .post(this.deliveryUrl,userRequest,options)
        .map((r:Response)=>r.json())
        .catch(this.handleError);
}

I've performed the same action passing data over a queryParam using short form (), and it made no difference in this case. I seem to be overlooking what is necessary to pull out the information with this one.

I've looked at both: Angular2 HTTP using observables subscribe showing data undefined and Angular 2 return data from service is not availabe after RxJs subscribe.

Which I'm passed where their questions were answered. What am I missing?


回答1:


It's unclear from your question where "outside" is, but if it's after the call where you get the Observable then this is expected behavior

someMethod() {
  this.checkoutService.getDisabledDate()
  .subscribe(
    // anything here is executed sometimes later when the response from the server arrives
    dates=>{ 
      this.formattedDate=dates;
      // code that depends on the result goes here
    }, 
    (error:any)=>{console.log(error)}
  );
  // this is executed first
}

You can't get the value outside of subscribe. You can use map and return the result for the caller to subscribe, like done in getDisabledDate or you move the code to one of the callbacks.



来源:https://stackoverflow.com/questions/41945817/observable-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!