Angular2 记录 http 响应

标签 angular typescript rxjs

服务.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); 

控制台写入“日志创建的类别 ID 未定义”,但服务器返回 ID。如何在 service.ts 本身内记录 http 响应。

最佳答案

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

关于Angular2 记录 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383090/

相关文章:

http - 如何进行http调用而不订阅响应

angular - 如何使用 highcharts 和 angular 启用 noData

angular - 如何使用 Observable 订阅行为主题

Angular2 Get 请求被发出两次

angular - 如何在 Vagrant 的共享文件夹上使用 "ng new"创建 Angular 应用程序?

javascript - github 上的 Angular 全栈示例

javascript - 使用 Aurelia 对 Blur 进行现场验证

javascript - Angular 7 标题未设置

node.js - 将 Sinon SinonStubbedInstance 与 Typescript 一起使用

angular - 有没有更好的方法让我在 Angular 中缓存 HTTP 请求?