Angular 4.0 http放置请求

时间:2017-09-26 07:20:27

标签: javascript angular http typescript

我已经写了一个函数来发送一个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);
}

有人可以解释一下,为什么第一个功能不起作用但第二个功能正常工作?

3 个答案:

答案 0 :(得分:2)

Observable是懒惰的,你需要订阅它们才能让它们工作并检索任何东西。你订阅了你的方法吗?例如:

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,它基于角度2,大部分功能在角度4中有效,有一个专门用于http请求的部分:https://angular.io/tutorial/toh-pt6

答案 1 :(得分:1)

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

所以,基本上你是在创造一种它正在起作用的幻觉,当它不是时。

可能最好用PostMan之类的东西来测试你的API,看看你是否可以先使用它。

答案 2 :(得分:0)

您错误地使用了map方法,请在文档中详细了解此方法:http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/map.html

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

cmd.Parameters("@Street").Value = strStreet.GetDBNullIfEmpty

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

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方法返回Observable对象,因此您可以订阅它并等待响应,错误或简单的完整方法(subscribe()的第三个参数): http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/subscribe.html