角rxjs。结合多个可观察物

时间:2018-12-06 21:41:45

标签: angular rxjs

我有2个可观察值:

  1. this.configsService.getConfigsList()
  2. this.bcProductService.getProductById(config['id'])

我可以同时订阅它们和使用它们的数据。

我想获取配置列表,并将每个配置项与其对应的产品(使用config.id)进行映射...类似这样的东西。

    const configs = this.configsService.getConfigsList;
    const product= (id)=> this.bcProductService.getProductById(id);
    configs.pipe(
        concatMap(val => product(val['id']).map(t=>val['p']=t) )
    ).subscribe(test => {
        console.log('configs with products: ', test);
    });

但这不起作用。以上不会显示错误或console.log。我在网上看到了几个例子,但我似乎可以使它正常工作。谢谢您的帮助。

另一次尝试

这是https://www.learnrxjs.io/operators/combination/combinelatest.html的示例,但出现以下错误。

  

core.js:1673错误,TypeError:combinedProject.subscribe不是函数

configsWithP(): any {
    const configs = this.configsService.getConfigsList;
    const product = this.bcProductService.getProductById(124);
    const combinedProject = combineLatest( configs, product, (c, p) => {
        return `c: ${c}, p: ${p}`;
    });
    // log values
    const subscribe = combinedProject.subscribe(latestValuesProject =>
        console.log(latestValuesProject)
    );
}

1 个答案:

答案 0 :(得分:0)

在聊天中讨论答案并提出解决方案后,更新了答案。 getConfigLists返回一个Observable,它发出配置对象数组。然后,对于数组中的每个对象,需要从服务中检索相应的产品,然后将其与config对象合并。之后,它需要再次以可观察到的形式发出,发出配置对象数组。

这是解决方案:

private configsWithP(): any {
  const configs = this.configsService.getConfigsList;
  const combinedConfigs = configs.pipe(
    flatMap((configsArray) => {
      const getProductObservablesArray = configsArray.map((config) => this.bcProductService.getProductById(124));
      return zip(...getProductObservablesArray, (...args: any[]) => args).pipe(
        map(products => {
          for (let i = 0; i < configsArray.length; i++) {
            configsArray[i]['p'] = products[i];
          }
          return configsArray;
        })
      )
  }));
  combinedConfigs.subscribe(configss=> {
    console.log(configss);
  });
}

这也是StackBlitz上有效的示例。我没有创建服务,而是创建了可观察对象并将它们组合在一起。检查那里的控制台,您将看到输出。

相关问题