Mark
Mark

Reputation: 2587

Angular2 http observable

I have the below method that calls an http observable

SaveWorkRequest(workRequest: any) {
    let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers }); // Create a request option
    let url = 'deployment/SaveWorkRequest';
    let dto = { 'workResponse': workRequest };

    //   post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
    return this.http.post(GlobalVariables.SITE_ROOT + url, dto, options)
        //.toPromise()
        //.then(this.extractData) //...and calling .json() on the response to return data
        .map(this.extractData)
        .catch(this.handleError);   
}

//
private extractData(res: Response) {
    let body = res.json();
    console.log(body);
    return body || {};
}

And this code in a component that calls it

        let response = this.workRequestService.SaveWorkRequest(this.workRequest)
        .subscribe(
            hero => this.message = hero,
            error => this.errorMessage = <any>error);



    console.log(this.message);

The problem is, the code in the component returns before the service method. So console.log(this.message) is undefined. It must be a timing problem i guess?

Upvotes: 1

Views: 95

Answers (3)

HirenParekh
HirenParekh

Reputation: 3735

Yes, this is the timing issue. console.log(this.message); statement get executes before the response arrives from your http request. you should write the log statement inside subscribe as follows.

let response = this.workRequestService.SaveWorkRequest(this.workRequest)
    .subscribe(
        hero => 
        {
           this.message = hero;
           console.log(this.message);
        },
        error => this.errorMessage = <any>error);

Upvotes: 1

Calvin Ferrando
Calvin Ferrando

Reputation: 4082

Observable is asynchronous. If you try to console.log(this.message); you will get undefined value until the subscribe value is there.

On the template, just add {{ this.message?.some_property }} if you concern with the error might come out.

Upvotes: 0

elmiomar
elmiomar

Reputation: 2012

Try this:

ngOnInit() {
     this.getMessage().subscribe(_ => {
       console.log(this.message)
   });
}

public getMessage() {
  return this.workRequestService.SaveWorkRequest(this.workRequest)
    .map(hero => this.message = hero,error => this.errorMessage = <any>error);

Upvotes: 0

Related Questions