Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

angular - Observable Undefined

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...