Gelso77
Gelso77

Reputation: 1895

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

Upvotes: 6

Views: 9446

Answers (2)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

In RXJS, inside map operator, you need to return values will be received when observer subscribes.

    @Effect() 
  loadTasks$: Observable<Task[]> = this.actions$
    .ofType(fromActions.ADD_TASK).pipe(
    switchMap(() => ({this.taskService.GetTasks().map(data => {
            return data; })            
      })) 

    );

Upvotes: 5

erhise
erhise

Reputation: 311

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

Upvotes: 2

Related Questions