【问题标题】:Resolve objects in array from observables从可观察对象解析数组中的对象
【发布时间】:2021-05-18 01:47:06
【问题描述】:

我有一个关于解析数组中的 observables 的问题。 (使用 Angular 11)

首先,我想描述一下场景。假设我们有一个带有 ag-grid 的组件

table.component.html

    <ag-grid-angular
      [rowData]="data"
      [columnDefs]="columnDefs"
    >
    </ag-grid-angular>

rowData 类似于

[
  {id:0, user: 'userName1', valueBefore: 1, valueAfter:2},
  {id:1, user: 'userName1', valueBefore: 3, valueAfter:4},
  ...
]

还没有什么花哨的 - 但是,valueBeforevalueAfter 的 ID 需要解析为它们的名称。为此,必须完成 http 请求,例如HTTP GET /name/1 返回{id:1, name: 'one'}

很遗憾,我看不出有什么好的方法。

我看到了一种解决方案,例如先获取所有名称。然后,在一个画笔中更新rowData 对象,以便表格只重新渲染一次。 但是我必须维护一组我不喜欢的id/name 对。

我不知道我是否遗漏了一些我可以在这里使用的功能。

你有什么想法吗?你会如何解决这个问题?

谢谢!

【问题讨论】:

  • 如果可能的话,在首先获取 rowData 的同时在后端使用连接查询获取这些数据。我建议不要调用 API 来获取列表中每个用户的名称。例如:如果您的 rowData 中有 100 行,您最终将在应用程序中对 valueBefore 和 valueAfter 进行 200 次 API 调用。那只是为了渲染一个网格。不好。
  • 您应该能够按照您的建议预取所有名称,并重建您的 rowData 以包含“{ id: number, name: string }”类型的 valueBefore/valueAfter。无需管理外部对阵列。我没有使用过 ag-grid,但我很确定它可以绑定到复杂对象的属性(例如 valueBefore.name)。

标签: angular rxjs frontend ag-grid rxjs-observables


【解决方案1】:

实际上,使用 RxJS 很容易维护加载的值。只需将此代码添加到组件:

    cacheTimeout = 60 * 1000;
    valueCache = new Map<number, Observable<string>>();
    getValue$ = (id: number) => {
      if (!this.cache.get(id)) {
        this.cache.set(id, this.http.get('/name/'+id.toString()).pipe(
          map(result => result.name),
          publishReplay(1, this.cacheTimeout),
          refCount(),
          take(1),
        ));
      }
      return cache.get(id);
    }

并在模板中使用getValue$(id) | async

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 2019-09-09
    • 2012-04-20
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多