Angular Http does not work. Promise mixed with observable approach

I am trying to publish data for an internal Node js file from Angular. After submitting the form, the 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 happens here. I do not receive any error messages. Can you suggest anything about this?

+4
source share
2 answers

Each function Httpthat returns Observablemust have a method attached to it .subscribe(). If you skip this method, the request will not be executed. Therefore, attach .subscribe()to each function.

, : Promise style Observable style, .

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

, @Suren, . toPromise(), Promise:

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

import 'rxjs/add/operator/toPromise'
+3

Source: https://habr.com/ru/post/1658092/


All Articles