服务.ts
create(category: Category): Observable<Category> {
let body = JSON.stringify(category);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl+'categories', body, options)
.map(res => <Category> res.json() )
.catch(handleError);
}
组件.ts
this.categoryService.create(this.category)
.subscribe(
c => this.category = c,
error => this.errorMessage = <any>error);
console.log("created category ID " + this.category.id);
this.categories.push(this.category);
控制台写入“日志创建的类别 ID 未定义”,但服务器返回 ID。如何在 service.ts 本身内记录 http 响应。
最佳答案
this.categoryService.create(this.category)
.subscribe(
c =>{ this.category = c
console.log("created category ID " + this.category.id); //<<<access here
this.categories.push(this.category);
},
error => {this.errorMessage = <any>error)}
);
关于Angular2 记录 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383090/