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?
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*/);
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With