繁体   English   中英

角rxjs。 结合多个可观察物

[英]Angular rxjs. combine multiple observables

我有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)
    );
}

在聊天中讨论了答案并提出解决方案后,更新了答案。 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的示例。 我没有创建服务,而是创建了可观察对象并将它们组合在一起。 检查那里的控制台,您将看到输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM