Angular rxjs. combine multiple observables

旧时模样 提交于 2019-12-25 00:29:36

问题


I have 2 observables:

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

I can subscribe to both of them and use their data.

I want to get the configs list and map each config item with its corresponding product (using the config.id)... Something like this.

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

but that is not working. the above does not print an error or the console.log. I see several examples of this online but i just can seem to get it working. Thank you for helping.

another attempt

this is the example from https://www.learnrxjs.io/operators/combination/combinelatest.html but i get the following error.

core.js:1673 ERROR TypeError: combinedProject.subscribe is not a function

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:


Updated answer after we discussed it in chat and made a solution. The getConfigLists returns an Observable that emits arrays of config objects. Then for every object in the array the corresponding product needs to be retrieved from a service and merged with the config object. After that it needs to again come out as an observable that emits the array of config object.

This is the solution:

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

Here is also a sample on StackBlitz that works. I did not create services I create observables and combine them. Check the console there and you will see the output.



来源:https://stackoverflow.com/questions/53660102/angular-rxjs-combine-multiple-observables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!