angular - Angular2 記錄 HTTP 回應
服務.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);
控制台寫出「log created category ID undefined」,但伺服器回傳了 id。如何在 service.ts 中直接記錄 HTTP 回應。
答案#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)}
);
答案#2
你需要將依賴回應的程式碼移動到 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);
