合并两个RxJS Observable / Subscription,并遍历它们的数据

时间:2019-04-10 14:42:10

标签: angular typescript rxjs observable angular-httpclient

我使用Angular(版本7)和RxJS,并进行了两个api调用,每个返回可观察的对象,然后我订阅了。

现在,我必须合并这些订阅,因为来自两个可观察对象的数据是相互依赖的,并且我需要它们实现某些功能(例如,一个检查从subcription2接收的id的过滤器是否出现在subscription1中,然后才返回某些内容。 )。

由于我的代码很长,因此我准备了一个较小的示例版本,并用注释标记了我的重要位置:

getSomething(){
    /**
     * anIdFromSubscriptionTwo: An id that I need from subscription2
     */
    const subscription1 = this.service.getSomeStuff().subscription((someStuff) => {
        this.someStuff = stuff;
        this.someStuff.forEach((stuff) => {
            if(stuff.someProperty !== null && stuff.id === anIdFromSubscriptionTwo){
                ...
            }
        });
    } 

    /**
     * aIdFromSubscriptionOne: An id of type string that I get in the forEach loop inside of subscription1
     * aTypeFromSubscriptionOne: A type of type string that I get in the forEach loop inside of subscription1
     */
    const subscription2 = this.service.getSomeOtherStuff(aIdFromSubscriptionOne: string, aTypeFromSubscriptionOne: string).subscription((someOtherStuff) => {
        this.someOtherStuff = someOtherStuff;
        this.someOtherStuff.forEach(() => {
            // This is the only if statement I need, after combining the two subscriptions
            if(subscription1.stuff.someProperty !== null && subscription1.stuff.id === someOtherStuff.id){
                const properties: Image = {
                    id: // an id I need from subscription1
                    class: // a class I need from  subscription1
                    type: // a type I need from subscription2
                    ref: // a reference to the image url from subscription2
                    ...
                }
            }
        })  
    });
}

如何合并这两个订阅,以便可以在forEach循环中访问它们的数据并进行比较或正常使用?

1 个答案:

答案 0 :(得分:0)

您使用 switchMap 避免在另一个内部进行订阅

import { switchMap } from 'rxjs/operators';


  this.service.getSomeStuff().pip(switchMap((someStuff) => {
        this.someStuff = someStuff;

      this.service.getSomeOtherStuff(aIdFromSubscriptionOne: string, aTypeFromSubscriptionOne: string)
       ).subscribe((someOtherStuff) => {
        this.someOtherStuff = someOtherStuff;
        this.someOtherStuff.forEach(() => {
        // make a foreach loop here on someStuff to check if someOtherStuff exist in some Stuff
          this.someStuff.foreach((somestuff) => {
             if(somestuff.someProperty !== null && somestuff.id === someOtherStuff.id){
               const properties: Image = {
                id: // an id I need from subscription1
                class: // a class I need from  subscription1
                type: // a type I need from subscription2
                ref: // a reference to the image url from subscription2
                ...
               }
             }
           });  
         }); 
      });   
  });