vels4j vels4j - 1 month ago 21
TypeScript Question

Angular2 logging http response

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


console writes "log created category ID undefined" but server returns with id. how to log the http response within service.ts itself.

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