首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >刷新页面时会丢失有关用户的信息?Angular 2+ NgRx商店

刷新页面时会丢失有关用户的信息?Angular 2+ NgRx商店
EN

Stack Overflow用户
提问于 2019-11-23 20:49:03
回答 4查看 992关注 0票数 1

我需要发布用户信息,但我正在丢失它来刷新。如何设置isAuthenticated变量,使我们在刷新时不会丢失值?也许你不需要看大部分代码,只为了告诉我如何修复它,现在你需要的是我的代码:

组件:

代码语言:javascript
运行
复制
  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);
    });

减速机:

代码语言:javascript
运行
复制
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;
        }
      }
    }

效果:

代码语言:javascript
运行
复制
  @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'
   });
  })
);

状态:

代码语言:javascript
运行
复制
export interface AppState {
  authState: auth.State;
}

export const reducers = {
  auth: auth.reducer
};

export const selectAuthState = createFeatureSelector<AppState>('auth');

你能告诉我一种在刷新时避免数据丢失的方法吗?如果你需要更多的信息,尽管问我。就目前而言,这是正确的。但是当我进行刷新时,我会丢失所有内容,但令牌在本地存储中。

更新我添加了这个,但再次没有工作

代码语言:javascript
运行
复制
  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];
EN

回答 4

Stack Overflow用户

发布于 2019-11-23 20:56:38

在刷新时丢失状态是很正常的。您将需要自己持久化状态,或者使用诸如https://www.npmjs.com/package/ngrx-store-localstorage之类的库。

票数 0
EN

Stack Overflow用户

发布于 2019-11-23 21:01:23

您可以将此值另存为浏览器的localStorage:

代码语言:javascript
运行
复制
localStorage.setItem("auth", JSON.stringify(this.isAuthentificated));

然后,当您访问应用程序时,获取值。

代码语言:javascript
运行
复制
this.isAuthentificated = JSON.parse(localStorage.getItem("auth"));

但是,当您注销时,您需要将localStorage上的值设置为false,或者删除该密钥。(我更喜欢第一个)

1) localStorage.removeItem("auth");

2) localStorage.setItem("auth", false);

票数 0
EN

Stack Overflow用户

发布于 2019-11-24 00:57:45

尝尝这个

代码语言:javascript
运行
复制
  export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
     return localStorageSync( {keys: ['auth'], rehydrate: true})(reducer);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59007801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档