Angular 7 with json-server - 如何检索post响应中返回的id?

问题描述 投票:1回答:1

使用以下http选项:

const httpOptions: any = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  }),
  observe: 'response'
};

我发送http帖子到json-server端点,如下所示:

return this.http.post(`${this.baseUrl}/events`, myEvent, httpOptions);

订阅该帖子的代码如下:

this.api.saveEvent(this.event).subscribe(data => {
  // Need to pick up the id from data (HttpResponse) here
});

This is the returned HttpResponse object

我可以看到在订阅中返回的dataHttpResponse类型 - 什么是强制转换data的正确方法,以便我可以获取响应的body属性并获取json-server返回的id属性?

更新:根据下面的评论,我最终得到了saveNewEvent方法来返回Observable<HttpRespponse<Event>>,但是这只有在我将http选项作为内联匿名对象传递时才有效。在const中设置选项并在post方法中引用该const不起作用,我还没弄清楚原因。有任何想法吗?

angular post httpresponse json-server
1个回答
0
投票

当您指定类型时,您可以获取数据,只需确保您的API正确返回它。

return this.http.post<{id: Number}>(`${this.baseUrl}/events`, myEvent, httpOptions);

this.api.saveEvent(this.event).subscribe(data => {
  console.log(data.id);
});
© www.soinside.com 2019 - 2024. All rights reserved.