angular - Angular2 HTTP yanıtını kaydetme


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);

}

bileşen.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); 

console "log created category ID undefined" yazıyor ama sunucu id ile dönüyor. http yanıtını service.ts içinde nasıl kaydedebilirim.

Cevap #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)}
    );

Cevap #2

Yanıtla ilgili olan kodu subscribe() içine taşumanız gerekiyor

         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);