【问题标题】:Passing params to withLatestFrom function将参数传递给 withLatestFrom 函数
【发布时间】:2018-12-07 09:01:40
【问题描述】:

我正在建立商店行动。 我的商店模型如下所示:

{
    entities: {[n:number]: Client},
    ids: number[],
}

我从与给定条件对应的后端获取 id。 然后我需要从后端获取那些尚未存储的实体。 但我不知道如何将获取的 id 传递给withLatestFrom 函数?

const params = {
    conditions,
    fields: ['id']
};
this.apiService.getList(params)
    .pipe(
    map(resp => {
      const ids: number[] = [];
      resp.map((item: Client) => {
        ids.push(+item.id);
      });
      return ids;
    }),
    withLatestFrom(this.checkEntities()), // how to pass ids ?
    tap(resp => {
      patchState({
        entities: resp[1],
        ids: resp[0],
        loading: false
      });
    })
    );

private checkEntities(ids: number[]) {
    const params: ApiWyszukiwarka = {
      conditions: {id: ids},
      fields: 'all'
    };
    return this.apiService.getList(params);
}

或者我做错了什么?

【问题讨论】:

标签: angular rxjs ngxs


【解决方案1】:

我想你可能想使用mergeMap 而不是withLatestFrom

mergeMap 允许您映射到可观察对象,然后“解包”该可观察对象。

this.apiService.getList(params)
    .pipe(
      map(resp => resp.map(item => +item.id),
      mergeMap(ids => this.checkEntities(ids)),
      tap(resp => {
        patchState({
          entities: resp[1],
          ids: resp[0],
          loading: false
        });
      })
    );

【讨论】:

  • 当我使用mergeMap 时,我得到entities 作为resp - 不是这两个观察值的数组:/
【解决方案2】:

不要使用withLatestFrom,而是使用concatMapwithLatestFrom 对来自其源 Observable 的每个发射调用其回调,同时保持订阅所有作为参数传递的 Observable,但这不是您需要的。您只想在获得 id 列表后调用 this.checkEntities(),然后创建一个新的 Observable 并订阅它。

所以使用concatMap 你会得到这样的东西:

map(resp => {
  ...
  return ids;
}),
concatMap(ids => this.checkEntities(ids))

【讨论】:

  • 当我使用concatMap 时,我得到entities 作为resp - 不是这两个观察值(实体和ID)的数组:/
  • 这显然只是你链中的重要部分。不知道拿到`this.checkEntities(ids)`后你想做什么
  • 对,我可以map checkEntities 并合并结果。谢谢
  • @piernik map checkEntities 是什么意思并结合结果?
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 2021-04-18
  • 1970-01-01
  • 2014-02-07
相关资源
最近更新 更多