Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
RaviTeja Avatar asked Dec 15 '22 03:12

RaviTeja


2 Answers

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*/);
like image 165
Suren Srapyan Avatar answered Dec 18 '22 11:12

Suren Srapyan


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'
like image 24
Shashank Agrawal Avatar answered Dec 18 '22 12:12

Shashank Agrawal