【问题标题】:Angular 5 Service httpClient Post - Title is not definedAngular 5 Service httpClient Post - 未定义标题
【发布时间】:2017-12-11 13:54:35
【问题描述】:

我正在尝试从 Angular 5 服务发布数据。

在我拥有的服务中:

导出类 DataService { 标题:'我的标题';

然后

postIt() {
    return this.httpClient.post<any>('http://jsonplaceholder.typicode.com/posts', title: 'sometitle');
}

然后从我的 app.cmponent.ts onInit 我有:

this.myDataService.postIt()
  .subscribe(
    res => {
      console.log(res);
    },
    err => {
      console.log("Error occured");
    }
  );

我遇到了错误:

 ERROR ReferenceError: title is not defined

我做错了什么?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    Post 请求接受第二个参数作为 json 主体,它是一个对象。当您尝试在 post call 中发送任何数据时,它应该是对象格式

    const body = {name: 'Brad'};
    
    http
    .post('/api/developers/add', body)
     // See below - subscribe() is still necessary when using post().
    .subscribe(...);
    

    以下是更多详情的链接 https://angular.io/guide/http

    【讨论】:

      【解决方案2】:

      试试这样:

      postIt() {
          return this.httpClient.post<any>('http://jsonplaceholder.typicode.com/posts', { title: 'sometitle' });
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-16
        • 1970-01-01
        • 2019-02-16
        • 2018-04-02
        • 1970-01-01
        相关资源
        最近更新 更多