NGRX 效果调度了一个无效的动作

NGRX effect dispatched an invalid action

我正在尝试为我的操作创建一个 @Effect()。当我 运行 类型为 AuthenticationUserLoad 的操作时,我得到一个错误。

ERROR Error: Effect "AuthenticationEffects.getUser$" dispatched an invalid action: [object Object]

这是我的 Effect 代码

    @Effect()
      getUser$ = this.actions$.pipe(
       ofType(AuthenticationUserActions.AuthenticationUserTypes.AuthenticationUserLoad),
       map((action) => {

          return this.authService.getUser().pipe(
            map((user: User) => new AuthenticationUserActions.AuthenticationUserLoadSuccess({user})),
            catchError(error => of(new AuthenticationUserActions.AuthenticationUserLoadFailure({error})))

          );
        })
     );

更新

我将 map 更改为 switchMap 并且有效。

 @Effect()
  getUser$ = this.actions$.pipe(
    ofType(AuthenticationUserActions.AuthenticationUserTypes.AuthenticationUserLoad),
    switchMap((action) => {

      return this.authService.getUser().pipe(
        map((user: User) => new AuthenticationUserActions.AuthenticationUserLoadSuccess({user})),
        catchError(error => of(new AuthenticationUserActions.AuthenticationUserLoadFailure({error})))
      );
    })
  );

可能是我不明白map和switchMap的区别

map 运算符映射当前值,它不关心它是否是可观察的。 而 switchMapmergeMapconcatMap 期望回调到 return 一个可观察值,订阅它并发出它的值。

因此,当您调用 map 时,您说当前值应该转换为其他值。

map(action => return this.authService.getUser()),
// here the value is an observable stream, but not its emits.

当您调用 switchMap 时,您说现在我想订阅另一个流并发出它的值。因为它是 switchMap 它也表示一旦父流发出(相同的动作来)取消订阅当前的子流并再次订阅 this.authService.getUser() returns.[=20 的新调用=]

switchMap(action => return this.authService.getUser()),
// here the value is an emit from this.authService.getUser() stream.

在我的例子中,在动作调用中添加 { dispatch: false } 解决了问题。

getUser$ = createEffect(() => 
    this.actions$.pipe(
        ofType(actionName),
        withLatestFrom(this.store.select('app')),
        switchMap(() => {
            ...
        })
    ), { dispatch: false }
)