【问题标题】:Angular 4.0 http put requestAngular 4.0 http put 请求
【发布时间】:2017-09-26 07:20:27
【问题描述】:

我编写了一个函数来发送一个 http put 请求来更新一些数据,但它说它没有收到任何数据:

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data).map(
        response => response.json().data as Human,
        error => console.log(error)
    );
}

在我将功能更改为以下内容后,它正在工作:

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data).map(() => human);
}

谁能解释一下,为什么第一个功能不起作用,而第二个功能起作用?

【问题讨论】:

  • 也许这有帮助:如果我输出我的响应,如上所述,不起作用,我得到这个:响应 {_body: null, status: 204, ok: true, statusText: "无内容”,标题:标题,...} 标题:标题 _headers:映射(1){“内容类型”=> 数组(1)} _normalizedNames:映射(1){“内容类型”=>“内容类型"} proto : Object ok : true status : 204 statusText : "No Content" type : null url : "api/human/2" _body : null proto : Body

标签: javascript angular http typescript


【解决方案1】:

Observables 是惰性的,你需要订阅它们才能工作和检索任何东西。你订阅了你的方法吗?示例:

methodToUpdateHuman(human): void{
...
this.updateHuman(human).subscribe((response) => {
   //do something with the response
   console.log.("Response is: ", response);
},
(error) => {
   //catch the error
   console.error("An error occurred, ", error);
});
}

我建议你通读Angular Tour Of Heroses,它基于angular 2,大部分功能在angular 4 中起作用,有一个专门用于http 请求的部分:https://angular.io/tutorial/toh-pt6

【讨论】:

    【解决方案2】:

    在第二个示例中,您不是在地图中返回响应,而是返回最初传入的人类。

    所以,基本上你是在制造一种它在起作用的错觉。

    最好用 PostMan 之类的东西测试你的 API,看看你能不能先用它来工作。

    【讨论】:

      【解决方案3】:

      您错误地使用了 map 方法,请在文档中阅读有关此方法的更多信息:http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/map.html

      如果您想从服务器接收响应,您的代码应如下所示:

      updateHuman(human: Human) {
          const url = `${this.url}/${human.id}`;
          const data = JSON.stringify(human);
          return this.http.put(url, data).subscribe(
              response => response.json().data as Human,
              error => console.log(error)
          );
      }
      

      如果您想修改服务器响应(将一些对象映射到其他结构等),可以使用 map 方法:

      updateHuman(human: Human) {
          const url = `${this.url}/${human.id}`;
          const data = JSON.stringify(human);
          return this.http.put(url, data)
          .map(response => { return response.json() }) // you can get json response here 
          .subscribe(
              response => response.data as Human, // -- change here --
              error => console.log(error)
          );
      }
      

      map 方法返回 Observable 对象,因此您可以订阅该对象并等待响应、错误或简单的完成方法(subscribe() 的第三个参数): http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/subscribe.html

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2014-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-26
        相关资源
        最近更新 更多