Search code examples
observableactionngrxngrx-store

Ngrx: How to subscribe to a few actions in component?


I need to subscribe to a few actions and make them as one, otherwise it causing duplication pop up messages.

  ngOnInit(): void {
    forkJoin([
      this.actions.pipe(ofType(userActions.updateUserFail)),
      this.actions.pipe(ofType(brandActions.updateBrandFail)),
    ]).subscribe(() => {
      this.toastr.error(userInfoFailMsg);
    });
  }

But this does not works.


Solution

  • ForkJoin only emits values if all source observables complete, see https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin.

    Actions are per definition a never ending stream. I think what you want is: https://www.learnrxjs.io/learn-rxjs/operators/combination/merge Like this:

     ngOnInit(): void {
        merge([
          this.actions.pipe(ofType(userActions.updateUserFail)),
          this.actions.pipe(ofType(brandActions.updateBrandFail)),
        ]).subscribe(userInfoFailMsg => {
          this.toastr.error(userInfoFailMsg);
        });
      }
    

    With actions, this actually should work as well:

     ngOnInit(): void {
          this.actions.pipe(ofType(
             userActions.updateUserFail, 
             brandActions.updateBrandFail)
          ).subscribe(userInfoFailMsg => {
          this.toastr.error(userInfoFailMsg);
        });
      }