2

Can't figure out how to subscribe to the desired method of an Angular service depending on the conditional statement

  // this.someService.someMethod depending on the conditional statement
  .pipe(takeUntil(this.unsubscribe$))
  .subscribe((items) => {
    this.someData = items;
  });
  • UPD: For example I have a service with methods making http calls to the REST API and I have to make a different call depending on the current route. – Constantine Rafikov Jan 23 '22 at 01:12
  • How many different service methods are there? Do the methods return an observable? More context would be good. – wlf Jan 23 '22 at 04:13

2 Answers2

5

You can use the RxJs Conditional Operator iff to achieve that if both of your services return an Observable or a Promise.

The iff operator takes 3 arguments, first when being your condition, 2nd and 3rd being your different services that return an Observable/Promise.

If the condition is true subscribe to the first observable, if it is false subscribe to the second observable

 iif(
      () => {
           //Add your condition here
           return a + b === 4;
         },
         this.someService.someMethodWhenTrue(),
         this.someService.someMethodWhenFalse()
     )
     .pipe(takeUntil(this.unsubscribe$))
     .subscribe((items)=> {
         this.someData = items;
     });

I recommend you to read this https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif

HassanMoin
  • 2,024
  • 1
  • 6
  • 16
2

You could do following, if there might be different services to use:

let source$: Observable<any>;

if ( conditionA ) {
  source$ = this.someService.someMethodA()
} else {
  source$ = this.someService.someMethodB()
}

source$
  .pipe(takeUntil(this.unsubscribe$))
  .subscribe((items) => {
    this.someData = items;
  });

or only saving method name if there is only one service to use. Also it depends on what is more readable to you.

let methodName: string;

if ( conditionA ) {
  methodName = 'someMethodA';
} else {
  methodName = 'someMethodB';
}

this.someService[methodName]()
  .pipe(takeUntil(this.unsubscribe$))
  .subscribe((items) => {
    this.someData = items;
  });
Lukasz Gawrys
  • 1,234
  • 2
  • 8