Объедините две наблюдаемые / подписки RxJS и переберите их данные - PullRequest
0 голосов
/ 10 апреля 2019

Я работаю с Angular (Версия 7) и RxJS и совершаю два вызова API, каждый из которых возвращает наблюдаемый, на который я затем подписываюсь.

Теперь мне нужно объединить эти подписки, потому что данные из обеих наблюдаемых являются взаимозависимыми, и мне нужны они для реализации определенных функций (например, фильтр, который проверяет, получен ли идентификатор, полученный из подписки2, появляется в подписке 1, и только потом что-то возвращает. .).

Поскольку мой код очень длинный, я подготовил уменьшенный образец его версии и отметил для меня важные места с комментариями:

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 голосов
/ 10 апреля 2019

вы используете 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
                ...
               }
             }
           });  
         }); 
      });   
  });
...