我需要发布用户信息,但是我丢失了刷新信息。如何设置 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');
您能告诉我一种避免刷新时丢失数据的方法吗? 如果您需要更多信息,请问我。 现在一切正常。但是当我刷新时,我丢失了所有东西,但令牌在本地存储中。
UPDATE UPDATE UPDATE 我被添加了,但再次没有工作
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];