ngrx在效果期间两次reduce调用

时间:2019-05-15 20:24:18

标签: ngrx ngrx-effects ngrx-reducers

我正在使用使用ngrx的有角度的应用程序进行开发。我在下面定义了实现加载指示器的约定:

  • 每个实体的初始状态设置为null
  • 将其设为空对象,开始生效
  • 使用获取的数据填充效果完成

现在我的影响之一是:

  @Effect()
  LoginUser$ = this._actions$.pipe(
    ofType<LoginUser>(EUserActions.LoginUser),
    switchMap((params) => { new LoginUserSuccess(<IUser>{}); return of(params); }), // for loading indicator to be shown
    switchMap((params) => this._userService.loginUser(params.payload)),
    switchMap((currentUser: IUser) => of(new LoginUserSuccess(currentUser)))
  )

,但是不会在第一个switchMap中进行reducer调用。有什么问题。

2 个答案:

答案 0 :(得分:0)

效果是一个流,只会分派流中的最后一个动作。

根据您的情况,您可以在减速器中收听LoginUser并清空状态。

答案 1 :(得分:0)

我终于以其他方式解决了我的问题。我现在在主要动作内部调度另一个动作以更新状态。例如,这就是我的做法:

user.service.ts

export class UserService {
  constructor(private _store: Store<IAppState>) { }

  loginUser(model): void {
    this._store.dispatch(new AddBusy(EUserActions.LoginUser));
    this._store.dispatch(new LoginUser(model));
  }

  getAllUsers(): void {
    this._store.dispatch(new AddBusy(EUserActions.GetAllUsers));
    this._store.dispatch(new GetAllUsers());
  }
}

user.actions.ts

export class UserEffects {

  @Effect()
  LoginUser$ = this._actions$.pipe(
    ofType<LoginUser>(EUserActions.LoginUser),
    switchMap((params) => this._userLogic.loginUser(params.payload)),
    switchMap((currentUser: IUser) => { this._store.dispatch(new RemoveBusy(EUserActions.LoginUser)); return of(currentUser); }),
    switchMap((currentUser: IUser) => of(new LoginUserSuccess(currentUser)))
  )

  @Effect()
  getAllUsers$ = this._actions$.pipe(
    ofType<GetAllUsers>(EUserActions.GetAllUsers),
    switchMap(() => this._userLogic.getAllUsers()),
    switchMap((users: IUser[]) => { this._store.dispatch(new RemoveBusy(EUserActions.GetAllUsers)); return of(users); }),
    switchMap((users: IUser[]) => of(new GetAllUsersSuccess(users)))
  )

  constructor(
    private _userLogic: UserLogic,
    private _actions$: Actions,
    private _store: Store<IAppState>,
  ) { }
}

这很好地解决了我的问题。