2

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.

2 Answers 2

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)}
    );
Sign up to request clarification or add additional context in comments.

Comments

1

You need to move the code that depends on the response move into 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);

2 Comments

after moving this.categories.push(this.category); inside it worked, thanks. However the log outside being invoked earlier than subscribe.
Ups, forgot to move that in as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.