【问题标题】:Angular Typescript access specific JSON object by id in an observableAngular Typescript 通过可观察对象中的 id 访问特定的 JSON 对象
【发布时间】:2019-03-11 15:58:52
【问题描述】:

我在下面有这个 json 字符串,我想根据给定请求所需的任何一个来提取“股票”数据数组或“联系人”数据数组:

[{
  "id": "stocks",
  "name": "Stocks",
  "data": [
    {
      "id": 1,
      "name": "Actuant Corporation",
      "symbol": "ATU"
    },
    {
      "id": 2,
      "name": "Xilinx, Inc.",
      "symbol": "XLNX"
    }
  ]
},
{
  "id": "contacts",
  "name": "Contacts",
  "data": [
    {
      "id": 1,
      "full_name": "Betty Traise"
    },
    {
      "id": 2,
      "full_name": "Hank Hurrion"
    },
    {
      "id": 3,
      "full_name": "Calvin Ommanney"
    }
  ]
}]

例如,在下面的函数中,它是一个可观察的,假设有效负载参数是“联系人”。在这种情况下,我需要返回 "id: "contacts" 数据数组。这是我正在使用的代码:

  loadData$(payload: any = {}): Observable<any> {
  // paths: {
  //   titlemaps: 'http://localhost:4100/data'
  // },
  // return this.service.get(this.config.paths.titlemaps, payload);
  const JSON: any  = this.service.get(this.config.paths.titlemaps, payload);
  console.log('payload: ' + payload, 'json: ' + JSON); // if payload is "contacts", return only the contacts
  return JSON.find(data => data.id === 'contacts');
}

控制台日志按预期返回“联系人”和整个 JSON。但是,JSON.find 失败并出现错误:

ERROR TypeError: JSON.find 不是函数

当我稍微切换函数类型时,我得到 typescript 编译器错误:

[ts] 类型“Observable”上不存在属性“find”。

我错过了什么?

【问题讨论】:

  • 您的 tsconfig 文件中的 lib 设置是什么?
  • "lib": ["es2017","dom"],

标签: json angular rxjs observable


【解决方案1】:

您的服务调用的结果似乎是一个可观察的,您可以转换结果并使用 rxjs 管道运算符返回一个新值:

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

loadData$(payload: any = {}): Observable<any> {
   return this.service.get(this.config.paths.titlemaps)
     .pipe(
        map(result => result.find(data => data.id === payload))
      );
}

希望对你有帮助!

【讨论】:

    【解决方案2】:

    我将映射/查找操作移至服务,因为您将这些作为参数传递,但您当然不必那样做...

    https://stackblitz.com/edit/angular-2lajx4

    要点...

      get(url, payload) {
        return of(results)
        .pipe(map((res: any) => {
          return res.find(data => data.id === payload)
        }));
      }
    

    这里只是使用of()来模拟一个observable,结果就是你上面提供的JSON...

    loadData$ 订阅 get 并将数据放入变量中以供使用

      data: any;
    
      loadData$(payload: any = {}) {
        this.service.get('../results.json', payload).subscribe(data => {
          this.data = data
          console.log('payload: ' + payload, 'json: ' + this.data); // if payload is "contacts", return only the contacts
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2017-05-26
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2017-06-16
      相关资源
      最近更新 更多