【问题标题】:Angular NgRx type checking in app.reducer.ts errorsAngular NgRx 类型检查 app.reducer.ts 错误
【发布时间】:2021-05-19 07:35:35
【问题描述】:

我有一个简单的登录/注销状态管理。 我收到此错误:

类型 '(state: State | undefined, action: authActions) => State' 不可分配给类型 'ActionReducer'。 参数“action”和“action”的类型不兼容。 类型“Action”不可分配给类型“authActions”。 类型“操作”不可分配给类型“注销”。 属性“类型”的类型不兼容。 类型 'string' 不能分配给类型 'types.LOGOUT'。

这是我的文件。

auth.actions.ts

import { Action } from '@ngrx/store';
import { User } from '../user/user.model';

export enum types {
  LOGIN = '[AUTH] LOGIN',
  LOGOUT = '[AUTH] LOGOUT',
}

export class Login implements Action {
  readonly type = types.LOGIN;
  constructor(public payload: User) {}
}

export class Logout implements Action {
  readonly type = types.LOGOUT;
}

export type authActions = Login | Logout;

auth.reducer.ts

import { User } from '../user/user.model';
import * as authActions from './auth.actions';
export interface State {
  isLoggedIn: boolean;
  user: User | null;
}

const initialState: State = {
  isLoggedIn: false,
  user: null,
};

export function authReducer(
  state: State = initialState,
  action: authActions.authActions
): State {
  switch (action.type) {
    case authActions.types.LOGIN:
      return { ...state, isLoggedIn: true, user: action.payload };
    case authActions.types.LOGOUT:
      return { ...state, isLoggedIn: false, user: null };
    default:
      return state;
  }
}

app.reducer.ts

import { ActionReducerMap } from '@ngrx/store';
import * as fromAuthReducer from '../auth/store/auth.reducer';

export interface AppState {
  auth: fromAuthReducer.State;
}

export const appReducer: ActionReducerMap<AppState> = {
  auth: fromAuthReducer.authReducer,
};

【问题讨论】:

    标签: angular typescript ngrx typescript2.0


    【解决方案1】:

    这是使用ngrx 的旧语法的问题。您应该使用更好地支持 typescript 的 creator 语法。

    您的代码的解决方案是使用 any 类型的 ActionReducerMap:

    export const appReducer: ActionReducerMap<AppState, any> = {
      auth: fromAuthReducer.authReducer,
    };
    

    【讨论】:

    • 会使用任何导致错误的自动补全吗?
    • 不在这里。如果你不想使用any,你应该使用 createReducer/on 而不是你的 reducer 的 switch/case 语法
    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多