【问题标题】:what is the correct way to dispatch an action in angular?以角度调度动作的正确方法是什么?
【发布时间】:2019-01-13 23:49:17
【问题描述】:

你能告诉我什么是派发动作的正确方法吗?

在组件中,我们确实喜欢使用store 使用store.dispatch 而不是操作。

onLoginButtonClick(user: Authenticate) {
    this.store.dispatch(new Authctions.Login(user));
  }

现在使用ngEffect 我们调度动作而不使用store 只使用new Action name 为什么?

export class AuthEffect {
  @Effect()
  login$ = this.actions$.pipe(
    ofType(AuthActionsTypes.LOGIN),
    map((action: Login) => action.payload),
    switchMap((auth: Authenticate) => {
      return this.authService.login(auth).pipe(
        map(user => new LoginSuccess({user})),
        catchError(error => of(new LoginFailure(error)))
      );
    })
  );

为什么会这样使用

 new LoginSuccess({user})

我们可以这样使用this.store.dispatch( new LoginSuccess({user})) 吗?有效吗?

有什么更新吗?

【问题讨论】:

    标签: angular ngrx effects ngrx-store ngrx-effects


    【解决方案1】:

    效果返回动作,如文档here 状态。

    Ngrx 将在内部调度从您的效果返回的操作。

    您可以直接在效果中使用this.store.dispatch( new LoginSuccess({user}))但您不应该这样做,因为它不是必需的,只会使您的代码混乱

    如果您需要从效果中分派多个操作,您可以执行以下操作:

    @Effect() save = this.update$.pipe(
       map(action => action.payload),
       switchMap(payload => this.myService.save(payload)),
       switchMap(res => [
           new NotificationAction('save success'),
           new SaveSuccessAction(res)
       ])
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2011-01-17
      • 2022-01-14
      • 2019-02-08
      • 2020-01-21
      • 2018-09-05
      相关资源
      最近更新 更多