Javascript 无法通过使用NGXS更新存储来修补状态。我一直看到类型错误:无法冻结
我正在使用一个基本的Angular 11应用程序,它实现了身份验证(使用AWS Cognito&Amplify)。我想做的很简单。我正在使用内置的AWS放大方法来进行身份验证。我使用NGXS来存储身份验证相关的项目,如令牌、用户信息等Javascript 无法通过使用NGXS更新存储来修补状态。我一直看到类型错误:无法冻结,javascript,angular,state,ngxs,angular11,Javascript,Angular,State,Ngxs,Angular11,我正在使用一个基本的Angular 11应用程序,它实现了身份验证(使用AWS Cognito&Amplify)。我想做的很简单。我正在使用内置的AWS放大方法来进行身份验证。我使用NGXS来存储身份验证相关的项目,如令牌、用户信息等 import { State, Action, StateContext, Selector } from '@ngxs/store'; import { AuthStateModel, defaultAuthState } from './auth.model'
import { State, Action, StateContext, Selector } from '@ngxs/store';
import { AuthStateModel, defaultAuthState } from './auth.model';
import {
LoginAction,
AuthenticationCheckAction,
LogoutAction,
} from './auth.actions';
import { Auth } from 'aws-amplify';
import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';
import { updateItem } from '@ngxs/store/operators';
@State<AuthStateModel>({
name: 'authState',
defaults: defaultAuthState,
})
@Injectable()
export class AuthState {
cognitoClientId = environment.cognitoClientId;
cognitoCallbackURL = environment.cognitoCallbackURL;
cognitoDomainName = environment.cognitoDomainName;
loginurl = `https://${this.cognitoDomainName}/login?response_type=code&client_id=${this.cognitoClientId}&redirect_uri=${this.cognitoCallbackURL}`;
@Selector()
static getIsLoggedIn(state: AuthStateModel) {
console.log('from getIsLoggedIn selector =>', state);
return state.isLoggedIn;
}
@Action(LoginAction)
login() {
window.location.assign(this.loginurl);
}
@Action(AuthenticationCheckAction)
checkLogin({ getState, patchState }: StateContext<AuthStateModel>) {
const state = getState();
Auth.currentAuthenticatedUser()
.then((currentUser) => {
const isLoggedIn = true;
const username = currentUser?.attributes?.name;
patchState({
currentUser,
isLoggedIn,
username,
});
})
.catch((err) => console.log(err));
return;
}
@Action(LogoutAction)
logout({ patchState }: StateContext<AuthStateModel>) {
Auth.signOut()
.then((data) => {
console.log(data);
patchState(defaultAuthState);
})
.catch((err) => console.log(err));
return;
}
}
不了解这里发生了什么。这是修补状态的简单尝试。状态模型如下所示:-
export class AuthStateModel {
isLoggedIn: Boolean;
currentUser: Object;
username: String;
}
export const defaultAuthState: AuthStateModel = {
isLoggedIn: false,
currentUser: {},
username: '',
};
有什么办法可以让它正常工作吗?有时候,当我遇到这样的问题时,我无法更改对象,我只是克隆它。我通常使用lodash的cloneDeep进行以下操作:
patchState({
currentUser: _.cloneDeep(currentUser),
isLoggedIn,
username,
});
另外,尽量使您的状态可序列化。不熟悉AWS Cognito&Amplify,但是如果currentUser是一个对象,它有方法和其他绑定到它的成员,这是以后需要的,那么我不会将currentUser对象存储在状态中。你不想用内置方法存储对象是对的。我最好只是把相关的细节提取出来并储存在商店里,而不是扔掉不必要的垃圾。谢谢
export class AuthStateModel {
isLoggedIn: Boolean;
currentUser: Object;
username: String;
}
export const defaultAuthState: AuthStateModel = {
isLoggedIn: false,
currentUser: {},
username: '',
};
patchState({
currentUser: _.cloneDeep(currentUser),
isLoggedIn,
username,
});