【问题标题】:Angular NgRx dispatching action methodAngular NgRx 调度动作方法
【发布时间】:2020-01-20 10:20:50
【问题描述】:

所以我们有这个普通的效果doSomething官方发送另一个名为doSomethingElse的操作的方式是什么?该文档并没有真正说明正确的方法。最后可能没有太大区别,但我不太喜欢我可以在 95% 的代码库中使用 dispatch: false

使用dispatch: false 调度操作:

doSomething$ = createEffect(() =>
this.actions$.pipe(
  ofType(AuthActions.doSomething),
  map(() => AuthActions.doSomethingElse())
));

doSomethingElse$ = createEffect(
() =>
  this.actions$.pipe(
    ofType(AuthActions.doSomethingElse),
    tap(() => console.log('it works!'))
  ),
{ dispatch: false });

没有dispatch: false的调度动作:

doSomething$ = createEffect(
() =>
  this.actions$.pipe(
    ofType(AuthActions.doSomething),
    tap(() => {
      this.store.dispatch(AuthActions.doSomethingElse());
    })
  ),
{ dispatch: false });

doSomethingElse$ = createEffect(
() =>
  this.actions$.pipe(
    ofType(AuthActions.doSomethingElse),
    tap(() => console.log('it works!'))
  ),
{ dispatch: false });

两种解决方案都有效,但我不确定哪种是使用 NgRx 的正确方法。

【问题讨论】:

    标签: angular redux ngrx


    【解决方案1】:

    不推荐第二个。

    如果您没有映射到一个动作,下面的代码会报错,而设置{ dispatch: false } 会删除此检查,并且应该只用于副作用,例如导航,设置 localStorage 等。

    doSomething$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActions.doSomething),
      map(() => AuthActions.doSomethingElse())
    ));
    

    您的示例不清楚为什么需要执行两项操作。

    如果您想要一个通用的动作记录器,以下将起作用:

    /**
     * Log all actions in the console
     */
    
    export function logger(
      reducer: ActionReducer<RootStoreState.State>
    ): ActionReducer<RootStoreState.State> {
      return (state, action) => {
        const result = reducer(state, action);
        if (action.type.startsWith("[")) { <----FILTER TO ONLY USER CREATED ACTIONS (i.e. not router)---------
          console.groupCollapsed(action.type);
          console.log("prev state", state);
          console.log("action", action);
          console.log("next state", result);
          console.groupEnd();
        }
    
        return result;
      };
    }
    

    并在 app.module.ts

    export const metaReducers: MetaReducer<any>[] = !environment.production
      ? [logger]
      : [];
    
    @NgModule({
      imports: [
        ...
        StoreModule.forRoot(ROOT_REDUCERS, {
          metaReducers, <--------------------------------------KEY LINE-----------
          runtimeChecks: {
            strictStateImmutability: true,
            strictActionImmutability: true,
            strictStateSerializability: true,
            strictActionSerializability: true
          }
        }),
        ...
    

    【讨论】:

    • 对不起我的例子,我可能不够清楚; console.log 部分只是一个占位符,可以代替其他任何东西。关键是,我应该在我实际调度另一个动作并且不是副作用的情况下使用dispatch: false(不过我认为你已经回答了这个问题:))?
    • @Eyho 是的,仅将 dispatch: false 用于仅产生副作用的效果。它还可以更轻松地查看效果并了解其目的(映射到另一个动作/副作用)
    【解决方案2】:

    我将把它放在旧样式中,因为我还没有迁移到新的 ngrx 方式,但它也是一样的。

    Actions.ts

    export enum AuthActionTypes {
        SIGNUP = '[AUTH] SIGNUP',
        SIGNUP_SUCCESS = '[AUTH] SIGNUP_SUCCESS',
    }
    
    export class Signup implements Action {
        readonly type = AuthActionTypes.SIGNUP;
        constructor(public payload: any) { }
    }
    export class SignupSuccess implements Action {
        readonly type = AuthActionTypes.SIGNUP_SUCCESS;
    }
    
    export type AuthActions =
        Signup |
        SignupSuccess;
    

    效果

    @Effect()
        signup$: Observable<Action> = this.actions$.pipe(
            ofType(AuthActionTypes.SIGNUP),
            map((action: Signup) => action.payload),
            map((payload) => {
                  // whatever
                return new SignupSuccess(); // this come from AuthActions inner // action.ts, you are dispaching SignupSuccess();
            }),
    
    @Effect()
        signupSuccess$: Observable<Action> = this.actions$.pipe(
            ofType(AuthActionTypes.SIGNUP_SUCCESS),
            map((action: Signup) => action.payload),
            map((payload) => {
                  // whatever
                return new XAction(); 
            }),
    ```
    
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2020-01-25
      • 1970-01-01
      相关资源
      最近更新 更多