angularrxjssubject-observerrxjs-subscriptions

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

  • 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;
      });