我正在使用 Angular,我正在尝试使用 Redux 在我的项目中实现 JWT 身份验证和授权,但“Store.ts”引发了一个错误,指出以下内容:
{ "resource":
"/C:/Projects/AngularProjects/CarRental/src/app/redux/store.ts",
"owner": "typescript", "code": "2769", "severity": 8, "message":
"**No overload matches this call.\n Overload 1 of 2,** '**(reducer:
Reducer<appState, action>, enhancer?: StoreEnhancer<unknown, unknown>
| undefined): Store<appState, action>', gave the following error.\n
Argument of type '(currentState: appState, action: action) =>
appState' is not assignable to parameter of type 'Reducer<appState,
action>'.\n Types of parameters 'currentState' and 'state' are
incompatible.**\n Type 'appState | undefined' is not assignable
to type 'appState'.\n Type 'undefined' is not assignable to
type 'appState'.\n **Overload 2 of 2, '(reducer: Reducer<appState,
action>, preloadedState?:** { user: { userId?: number | undefined;
firstName?: string | undefined; lastName?: string | undefined;
identificationNumber?: number | undefined; ... 9 more ...; JwtToken?:
string | undefined; }; cars: { ...; }[]; } | undefined, enhancer?:
StoreEnhancer<...> | undefined): Store<...>', gave the following
error.\n **Argument of type '(currentState: appState, action: action)
=> appState' is not assignable to parameter of type 'Reducer<appState, action>'."**, "source": "ts", "startLineNumber": 5, "startColumn":
34, "endLineNumber": 5, "endColumn": 41 }
这是我为整个 Redux 基金会、它使用的模型和服务编写的代码。
我的 action-type.ts:
export enum actionType {
getAllCars,
Register,
LogIn,
LogOut,
GotError
}
我的 action.ts
import { actionType } from "./action-type";
export interface action {
type: actionType;
payLoad?: any;
}
我的 app-state.ts
import { carsModel } from '../models/cars.model';
import { userModel } from '../models/user.model';
export class appState {
public user: userModel = null as any;
public cars: carsModel[];
public constructor() {
this.cars = [];
this.user = JSON.parse(sessionStorage.getItem("user")!);
}
}
我的 reducer.ts
import { appState } from "./app-state";
import { actionType } from "./action-type";
import { action } from "./action";
export function reducer(currentState: appState, action: action): appState {
const newState = { ...currentState };
switch (action.type) {
case actionType.getAllCars: newState.cars = action.payLoad;
break;
case actionType.Register: newState.user = action.payLoad;
break;
case actionType.LogIn: newState.user = action.payLoad;
sessionStorage.setItem("item", JSON.stringify(newState.user));
break;
case actionType.LogOut: newState.user = null as any;
sessionStorage.removeItem("user");
break;
}
return newState;
}
我的 store.ts
import { createStore } from "redux";
import { reducer } from './reducer';
import { appState } from './app-state';
export const store = createStore(reducer, new appState());
我的 userModel.ts
export class userModel {
constructor (
public userId?: number,
public firstName?: string,
public lastName?: string,
public identificationNumber?: number,
public userName?: string,
public dateOfBirth?: Date,
public gender?: string,
public email?: string,
public passWord?: number,
public image?: File,
public imageFileName?: string,
public roleId?: number,
public role?: string,
public JwtToken?: string
) {}
}
我的汽车模型.ts
export class carsModel {
static cars: carsModel[];
constructor (
public id?: number,
public carTypeId?: number,
public manufacturer?: string,
public model?: string,
public yearOfManufacture?: number,
public gearBox?: string,
public name?: string,
public kilometrage?: number,
public usability?: string,
public availability?: string,
public vin?: number,
public branchName?: number,
public image?: File,
public imageFileName?: string,
public cars?: carsModel[]
) {}
}
我的 Auth.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CredentialsModel } from 'src/app/models/Credentials.model';
import { userModel } from 'src/app/models/user.model';
import { actionType } from 'src/app/redux/action-type';
import { store } from 'src/app/redux/store';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
public async register(user: userModel): Promise<Boolean> {
const formData = new FormData();
formData.append("firstName", user.firstName as string);
formData.append("lastName", user.lastName as string);
formData.append("identificationNumber", user.identificationNumber?.toString() as any);
formData.append("userName", user.userName as string);
formData.append("dateOfBirth", user.dateOfBirth as any);
formData.append("gender", user.gender as string);
formData.append("email", user.email as string);
formData.append("passWord", user.passWord as any);
formData.append("roleId", user.roleId?.toString() as any);
formData.append("image", user.image as any, user.image?.name);
try {
const registeredUser = await this.http.post<userModel>(environment.authURL + "/Register", formData).toPromise();
store.dispatch({ type: actionType.Register, registeredUser });
return true;
}
catch (httpErrorResponse) {
store.dispatch({ type: actionType.GotError, payLoad: httpErrorResponse });
return false;
}
}
public async Login(credentials: CredentialsModel): Promise<Boolean> {
try {
const LoggedInUser = await this.http.post<userModel>(environment.authURL + "/LogIn", credentials).toPromise();
store.dispatch({ type: actionType.LogIn, LoggedInUser });
return true;
}
catch (httpErrorResponse) {
store.dispatch({ type: actionType.GotError, payLoad: httpErrorResponse });
return false;
}
}
public LogOut(): void {
store.dispatch({ type: actionType.LogOut });
}
}
有人可以解释为什么这个错误不断弹出吗?
再次感谢您的帮助。
答案 0 :(得分:0)
你需要在reducer中提供一个默认状态:
我的 app-state.ts
import { carsModel } from '../models/cars.model';
import { userModel } from '../models/user.model';
export class appState {
public user: userModel = null as any;
public cars: carsModel[];
public constructor() {
this.cars = [];
this.user = JSON.parse(sessionStorage.getItem("user")!);
}
}
export const defaultAppState = new appState();
我的 reducer.ts
import { appState, defaultAppState } from "./app-state";
import { actionType } from "./action-type";
import { action } from "./action";
export function reducer(currentState: appState = defaultAppState, action: action): appState {
// omitted
}