Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Chris Avatar asked Sep 18 '25 17:09

Chris


1 Answers

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.

like image 197
Günter Zöchbauer Avatar answered Sep 21 '25 10:09

Günter Zöchbauer