Angular ngrx@effect 基本问题:Type 'Observable<void>' is not assignable to type

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

我想弄清楚@ngrx/effects 是如何工作的,但是在我的错误和我的 stackbliz 代码下面的这个简单示例中我遇到了一些问题

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'

感谢

在 RXJS 中,在 map 运算符内部,您需要 return 观察者订阅时会收到值。

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

    );

刚开始有几处错误

  • 您收到的错误是因为您需要 import { map } from 'rxjs/operators' 中的 pipe(map(data => ...)
  • 然后你需要添加dispatch: false,因为你没有return任何动作,否则你会陷入死循环。

两个选项

效果应该 return 动作或 dispatch: false

选项 1:无派发操作

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

选项 2:调度操作

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