在 Angular 中存储和处理来自 httpClient get 请求的 JSON 数据的最佳方式

best way to store and process JSON data from httpClient get request in Angular

我是 Angular 的新手,我正在使用 Ionic Angular 进行一个项目。我的目标是使用 httpClient 并向 api 国家/地区发送获取请求,该国家/地区将向我发送回所有国家/地区的 JSON。我用来存储数据的方式是创建一个与我从中接收的数据类型相匹配的接口,然后订阅该可观察对象并将数据存储到我定义的数据类型的数组中。

但是对于国家来说,我唯一需要的就是名称,是否可以将每个国家的名称存储到一个数组中而不定义接收对象的结构JSON,因为它很长和复杂。

这是我正在尝试执行的代码:

将国家/地区设置为可观察。在 Country.Service 文件中

  getCountry(): Observable<any>{
    return this.http.get<any>(this.url2);
  }

声明变量并存储国家数据:

public countries: any;

  storeCountry(){
    this.countryService.getCountry().subscribe(
      data => {
        this.countries = data;
      }
    );

这就是我想要做的,但我无法将数据放入国家/地区变量中以将其作为数组访问,当我控制台记录显示为未定义的国家/地区时。

实现我想要实现的目标的最佳方法是什么?我将不胜感激,

我假设你从后端收到的数据是结构

countries = [
  { 'name': 'USA', 'id': '1', ... },
  { 'name': 'UK', 'id': '2', ... },
  ...
]

在这种情况下,您可以从 GET 请求中删除 <any> 并使用 map() 方法仅获取国家/地区名称作为数组。尝试以下

服务

import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';

getCountry(): Observable<any>{
  return this.http.get(this.url2).pipe(map(countries => countries.map(country => country.name);
}

说明

如果您也是 Rxjs 的新手,那么您可能会对为什么有两个 map 函数感到困惑。

  1. pipe(map())部分属于Rxjs。

    • pipe() function can be used to modify and control the data flow using various Rxjs operators
    • 我们只使用一个运算符 map(),它将自定义函数投射到源可观察对象(JSON 从 API 返回)和 returns 结果值作为可观察到。
  2. 我们使用countries.map()中的map()函数来提供我们自定义的投影函数。它根据我们的回调创建一个新数组,仅使用源对象数组的 name 属性。

那你就可以在组件里订阅了

storeCountry(){
  this.countryService.getCountry().subscribe(
    countries => {
      this.countries = countries; // this.countries = ['USA', 'UK', ...]
    },
    error => {
      // handle error
    }
  );
}