Rav*_*ja 4 http typescript angular2-services angular
我正在尝试将数据发布到Angular的后端Node js文件中.表单提交后,函数调用:
cmdSubmit() : void
{
console.log(this.cli);
this.Cliservice.postdata(this.cli)
.then(clidata => this.clidata.push(clidata),
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
postdata功能代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但这里什么也没发生.我没有收到任何错误消息.你能就此提出一些建议吗?
Http返回的每个函数都Observable必须.subscribe()附加一个方法.当您错过此方法时,请求将不会执行.所以将.subscribe()方法附加到每个函数.
正如在评论中有人说,你正在使用两种方法:Promise style和Observable style,所以我建议你使用一个普通的款式.
this.http.post(this.runUrl, body, options)
.map(this.extractData).subscribe(/*here your parameters*/);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1225 次 |
| 最近记录: |