Search code examples
angulartypescriptngrxngrx-storengrx-effects

Angular ngrx@effect basic question : Type 'Observable<void>' is not assignable to type


I am trying to figure out how @ngrx/effects works, but I am having some problems in this easy example below my error and my stackbliz code

https://stackblitz.com/edit/redux-in-actions?file=src%2Fapp%2Fstore%2Feffects%2Ftask.effects.ts

Type 'Observable' is not assignable to type 'Observable'. Type 'void' is not assignable to type 'Action'

thank

enter image description here


Solution

  • There are a couple of things wrong just to start with

    • The error you are getting is because you need pipe(map(data => ...) from import { map } from 'rxjs/operators'.
    • Then you need to add dispatch: false since you are not returning any actions, otherwise you will get stuck in an endless loop.

    Two options

    An effect should either return an action or dispatch: false

    Option 1: No dispatched action

    @Effect({ dispatch: false }) 
    loadTasks$: Observable<void> = this.actions$.pipe(
       ofType(fromActions.ADD_TASK),
       switchMap(() => this.taskService.GetTasks().pipe(
          map(data => {             
            console.log(data);        
          })
       ) 
    ));
    

    Option 2: Dispatch action

    @Effect()
    loadTasks$: Observable<void> = this.actions$.pipe(
      ofType(fromActions.ADD_TASK),
      switchMap(() =>
        this.taskService.GetTasks().pipe(
          map(
            (data: Task[]) => new SomeActionYouGot(data);
          ),
          catchError(error =>
            of(new SomeOtherActionThatIndicatesFailFor(data))
          )
        )
      );