代码之家  ›  专栏  ›  技术社区  ›  Udi Mazor

从createAction函数获取类型

  •  0
  • Udi Mazor  · 技术社区  · 5 年前

    创建ngrx操作有两种方法。一个是定义一个实现Action类的新类,另一个是使用“createAction”函数。有没有办法获得使用“createAction”方法创建的操作的类型?

    例如,如果我有此操作:

    export const getWorker = createAction(
      '[Worker Api] Get Worker',
      props<{ workerId: number }>()
    );
    

    我希望workerId的效果能够监听该动作:

    getWorker$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(WeatherApiActions.getWorker),
      switchMap((action: { type: string, workerId: number }) => this.workerService.getWorker(action.workerId)),
      map((worker: IWorker) => WeatherApiActions.getWorkerSuccess({ worker }))
    )})
    

    像你一样,我不得不自己写。这使得效果与动作紧密耦合,这是一个巨大的缺点。所以我的问题是:我是否必须使用第一种创建动作的方法才能进行动作有效负载的键入?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Ray Megal    5 年前

    我对ng/ngrx等比较陌生,但使用create*helper方法的部分原因似乎是为了获得更好的类型支持。我也有同样的问题,我的一个影响是:

      authSignup = this.actions$.pipe(
        ofType(AuthActions.SIGNUP_START),
        switchMap((signupAction: AuthActions.SignupStart) => {
          return this.http.post<AuthResponseData>(
      ...
    

    为此:

      authSignup = createEffect(() =>
        this.actions$.pipe(
          ofType(AuthActions.signupStart),
          switchMap(({ email, password }) => {
            return this.http
              .post<AuthResponseData>(
      ...
    

    该操作看起来像:

    export const signupStart = createAction(
      "[Auth] Signup Start",
      props<{ email: string; password: string }>()
    );
    

    我花了一点时间才弄明白这一点;现在切换地图 知道 动作的道具是什么。而且,至少在最新的VSCode中,我在输入参数时得到了IntelliSense帮助。