NGRX效果发送了无效操作

问题描述 投票:4回答:1

我正在尝试为我的操作创建一个@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})))

          );
        })
     );

UPDATE

我将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之间的区别。

angular typescript ngrx ngrx-effects
1个回答
0
投票

map运算符映射当前值,它不在乎是否可观察。而switchMapmergeMapconcatMap希望回调返回一个可观察的值,对其进行订阅并发出其值。

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

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

当您呼叫switchMap时,您现在说我想订阅另一个流并发出其值。因为它是switchMap,所以它还说一旦父流发出(相同的动作),就从当前子流中取消订阅并再次订阅this.authService.getUser()的新调用返回的内容。

switchMap(action => return this.authService.getUser()),
// here the value is an emit from this.authService.getUser() stream.
© www.soinside.com 2019 - 2024. All rights reserved.