简体   繁体   English

如何从Angular中的HTTP请求返回JSON响应的特定属性?

[英]How do I return one specific attribute of a JSON response from a HTTP request in Angular?

I have a HTTP request to fetch details for a table. 我有一个HTTP请求来获取表的详细信息。 Earlier, the response was a JSON which looked like this : 之前,响应是一个看起来像这样的JSON:

{"TotalRejectedRequests":0,"TotalDrafts":41,"RequestsPendingApproval":6,"TotalApprovedRequests":13}

For this type of response, I was returning the data like this : 对于这种类型的响应,我正在返回如下数据:

return this.http.post<Snapshot>('https://xyz.abc/fetchData', details);

where Snapshot was the name of the interface to which the response was mapped. Snapshot是响应映射到的接口的名称。

Now the response that I get from the HTTP request has changed to this : 现在,我从HTTP请求获得的响应已更改为:

{
    "status": "SUCCESS",
    "data": {
        "TotalRejectedRequests": 0,
        "TotalDrafts": 2,
        "RequestsPendingApproval": 0,
        "TotalApprovedRequests": 1
    },
    "errorMsg": null
}

How do I now return only the value of "data" in this response JSON mapped to the Snapshot interface I already have? 现在如何在映射到我已有的Snapshot接口的此响应JSON中仅返回“数据”的值?

EDIT : Igor's answer solved the previous issue but I have 2 different issues now. 编辑:伊戈尔的答案解决了以前的问题,但我现在有2个不同的问题。 1. What do I do if I don't have any interface to map my response to? 1.如果我没有将响应映射到的界面怎么办? I have another service where I was just returning the entire JSON without mapping it to an interface? 我还有另一个服务,我只是返回整个JSON而没有将其映射到接口? Now I just want to return the data value of that JSON like shown above? 现在,我只想返回上面显示的JSON的数据值? How do I do that? 我怎么做?

  1. If I'm using subscribe or toPromise, will that cause any issue or will there be any other way to do it? 如果我使用的是subscription或toPromise,这会引起任何问题还是有其他解决方法?

Use map to map your data to the expected response. 使用地图, 地图数据的预期响应。

return this.http.post<{data: Snapshot}>('https://xyz.abc/fetchData', details)
   .pipe(map(_ => _.data));

Do not forget to import map 不要忘记导入map

import {map} from 'rxjs/operators';

Unwrap your data with rxjs mapping operator 使用rxjs映射运算符解包数据

import { map } from 'rxjs/operators';
...
return this.http.post<Snapshot>('https://xyz.abc/fetchData', details).pipe(
  map(({ data }) => data)
);

Also you can do a lot more with rxjs operators take look at their documentation 您还可以使用rxjs操作员做更多的事情,请查看他们的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM