1

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?

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.