HDs Sergiu
HDs Sergiu

Reputation: 1147

Subscription in subscription better writing in angular2+ with switchMap

Can someone please help me write this code better. I can't seem to understand switchMap, mergeMap and how to get rid of subscription in subscription.

this.service
  .service1('something')
  .pipe(takeUntil(this.unsubscribe))
  .subscribe(
    (s1result) => {
      if (s1result.IsOK) {
        this.service
          .service2()
          .pipe(take(1))
          .subscribe((s2result) => {
            'IS OK MESSAGE';
          });
      } else {
        'NOT OK MESSAGE';
      }
    },
    () => {}
  );

Upvotes: 0

Views: 43

Answers (1)

eko
eko

Reputation: 40647

You could use switchMap like this:

this.service
  .service1('something')
  .pipe(
       takeUntil(this.unsubscribe),
       switchMap((s1result)=> {
         if (s1result.IsOK) {
           return this.service
            .service2()
            .pipe(take(1));
        } else {
          return of(EMPTY);
        }
       })
  )
  .subscribe(
    (s2result) => {
      s2result ? 'IS OK MESSAGE' : 'NOT OK MESSAGE';
    });

Upvotes: 2

Related Questions