RaviTeja
RaviTeja

Reputation: 43

Angular Http Not working. Promise mixed with Observable approach

I'm trying to post the data to backend Node js file from Angular. After form submit below function is called:

cmdSubmit() : void 
{
       console.log(this.cli);
       this.Cliservice.postdata(this.cli)
                      .then(clidata  => this.clidata.push(clidata),
                            error =>  this.errorMessage = <any>error);

}

postdata function code:

postdata(obj: any): Promise<any> {
    alert('hello');
    let body = JSON.stringify({ obj });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.runUrl, body, options)
                    .map(this.extractData)
                    .catch(this.handleError);

    /*return this.http.post(this.runUrl, body, options)
                      .map(this.extractData)
                      .catch(res => {
             // do something

             // To throw another error, use Observable.throw
             return Observable.throw(res.json());
      });*/


    }

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

private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
                  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
 }

}

But nothing is happening here. I do not get any error message. Can you please suggest anything on this?

Upvotes: 4

Views: 1250

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68685

Every Http function which returns Observable must have a .subscribe() method attached to it. When you miss this method the request will not executed. So attach .subscribe() method to each function.

As was been said in the comments, you are using two approaches: Promise style and Observable style, so I advice you to use one common style.

this.http.post(this.runUrl, body, options)
         .map(this.extractData).subscribe(/*here your parameters*/);

Upvotes: 9

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

What @Suren mentioned is perfectly correct. As an alternative, you can also use the toPromise() method on this as well to directly convert it to a Promise object:

return this.http.post(this.runUrl, body, options).toPromise();

For this, you need to import the following

import 'rxjs/add/operator/toPromise'

Upvotes: 3

Related Questions