How can I subscribe to a different service method using a conditional statement?
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;
});
Solution 1:
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
Solution 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;
});