【发布时间】:2020-03-19 07:49:53
【问题描述】:
我需要发布用户信息,但我正在丢失它以刷新。如何设置 isAuthenticated 变量,我们不会在刷新时失去价值? 也许您不需要查看大部分代码,只需告诉我现在如何修复它 你需要的一段我的代码:
组件:
getState: Observable<any>;
isAuthenticated: false;
user = null;
errorMessage = null;
globalisAuthenticated = null;
constructor(public dialog: MatDialog, private store: Store<AppState>) {
this.getState = this.store.select(selectAuthState);
}
ngOnInit() {
this.getState.subscribe((state) => {
this.isAuthenticated = state.isAuthenticated;
this.user = state.user;
this.errorMessage = state.errorMessage;
// console.log("is" , this.isAuthenticated)
localStorage.setItem("isAuthenticated", state.isAuthenticated);
});
减速机:
export interface State {
// is a user authenticated?
isAuthenticated: boolean;
// if authenticated, there should be a user object
user: User | null;
// error message
errorMessage: string | null;
}
export const initialState: State = {
isAuthenticated: false,
user: null,
errorMessage: null
};
export function reducer(state = initialState, action: All): State {
switch (action.type) {
case AuthActionTypes.LOGIN_SUCCESS: {
return {
...state,
isAuthenticated: true,
user: {
token: action.payload.token,
email: action.payload.email
},
errorMessage: null
};
}
case AuthActionTypes.LOGIN_FAILURE: {
return {
...state,
errorMessage: 'Incorrect email and/or password.'
};
}
default: {
return state;
}
}
}
效果:
@Effect()
LogIn: Observable<any> = this.actions
.ofType(AuthActionTypes.LOGIN)
.map((action: LogIn) => action.payload)
.switchMap(payload => {
return this.authService.logIn(payload.email, payload.password)
.map((user) => {
console.log(user);
return new LogInSuccess({token: user.token, email: payload.email});
})
.catch((error) => {
console.log(error);
return Observable.of(new LogInFailure({ error: error }));
});
});
@Effect({ dispatch: false })
LogInSuccess: Observable<any> = this.actions.pipe(
ofType(AuthActionTypes.LOGIN_SUCCESS),
tap((user) => {
console.log("User", user);
localStorage.setItem('token', user.payload.token);
this.snackBar.open("Uspesno ste ste prijavili.", null, {
duration: 5000,
verticalPosition: 'bottom',
horizontalPosition: 'right'
});
})
);
状态:
export interface AppState {
authState: auth.State;
}
export const reducers = {
auth: auth.reducer
};
export const selectAuthState = createFeatureSelector<AppState>('auth');
您能告诉我一种避免在刷新时丢失数据的方法吗? 如果您需要更多信息,请问我。 目前这一切正常。但是当我刷新时,我会丢失所有内容,但令牌在本地存储中。
更新更新更新 我添加了这个,但又没有工作
import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';
import { reducers } from './reducers';
// const reducers: ActionReducerMap<IState> = {todos, visibilityFilter};
export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return localStorageSync({keys: ['todos']})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];
【问题讨论】:
-
您必须将
metaReducers添加到您的StoreModule,如下所示:StoreModule.forRoot(reducers, { metaReducers, ... }