service.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);
}
component.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);
控制台写入&#34;日志创建的类别ID未定义&#34;但服务器返回id。如何在service.ts本身内记录http响应。
答案 0 :(得分:1)
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)}
);
答案 1 :(得分:1)
您需要将依赖于响应的代码移动到subscribe()
this.categoryService.create(this.category)
.subscribe(
c => {
this.category = c;
console.log("created category ID " + this.category.id);
this.categories.push(this.category);
}),
error => this.errorMessage = <any>error);