【问题标题】:extract data from http response json从http响应json中提取数据
【发布时间】:2021-04-17 16:19:10
【问题描述】:

我正在尝试从带有角度的 JSON 响应服务中提取 firstname 字段并返回一个包含名字的数组。

这是 JSON 对象:

{
    "_shards": {
        "failed": 0,
        "skipped": 0,
        "successful": 1,
        "total": 1
    },
    "hits": {
        "hits": [
            {
                "_id": "BKZujHgB0urOc7uDCrf5",
                "_index": "names",
                "_score": 1.0,
                "_source": {
                    "firstname": "Alicia"
                },
                "_type": "_doc"
            },
            {
                "_id": "BaZujHgB0urOc7uDL7e2",
                "_index": "names",
                "_score": 1.0,
                "_source": {
                    "firstname": "Alice"
                },
                "_type": "_doc"
            }
        ],
        "max_score": 1.0,
        "total": {
            "relation": "eq",
            "value": 2
        }
    },
    "timed_out": false,
    "took": 4
}

这是我的service.ts

public autoComplete(name: string): Observable<Output> {
    const params = new HttpParams()
        .set('name', name);

    return this.httpClient.get<Output>(this.host, {params});
}

【问题讨论】:

  • 请为您的 service.ts 提供更多代码。它遗漏了很多东西,看起来您是在要求社区为您完成这项工作。你试过什么?什么没用?

标签: json angular service data-extraction


【解决方案1】:

你可以在订阅你的服务后试试这个:

let array = response.hits.hits.map(h=>h._source.firstname);

通常你会得到一个类似["Alicia", "Alice"]的数组。

【讨论】: