angular ngrx-store-localstorage 在重新加载后不存储数据

标签 angular authentication ngrx

我正在尝试使用 ngrx-store-localstorage 将 ngrx 集成到我的身份验证过程中,以跨浏览器 session 存储 token 。

当我登录时,我可以看到存储中 token 的值,如

{"token":{"token":"e5cb6515-149c-44df-88d1-4ff16ff4169b","expiresIn":10385,"expiresAt":1512082478397},"authenticated":true,"error":false}

但是当我编辑一个页面并重新加载应用程序时,我得到了

{"token":null,"authenticated":false,"error":false}

代码操作

import { Action } from '@ngrx/store';

import { AuthenticationTokenInterface } from '../authentication.interface';

export const LOGIN = 'LOGIN';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILED = 'LOGIN_FAILED';
export const LOGOUT = 'LOGOUT';
export const SET_TOKEN = 'SET_TOKEN';

export class Login implements Action {
  readonly type = LOGIN;
  constructor(public payload: {username: 'string',password: 'string'}) {}
}

export class LoginSuccess implements Action {
  readonly type = LOGIN_SUCCESS;
}

export class LoginFailed implements Action {
  readonly type = LOGIN_FAILED;
}

export class Logout implements Action {
  readonly type = LOGOUT;
}

export class SetToken implements Action {
  readonly type = SET_TOKEN;

  constructor(public payload: AuthenticationTokenInterface) {}
}

export type AuthenticationActions =  Login | LoginSuccess | LoginFailed | Logout | SetToken;

效果

@Injectable()
export class AuthenticationEffects {
  @Effect()
  login$ = this.actions$.ofType(AuthenticationActions.LOGIN)
  .pipe(
    mergeMap((action: AuthenticationActions.Login) => {
       return this.authenticationService.login(action.payload)
       .pipe(
        mergeMap((token:AuthenticationTokenInterface) => {
          this.router.navigate(['/main/dashboard']);
          return [
            { type: AuthenticationActions.LOGIN_SUCCESS },
            { type: AuthenticationActions.SET_TOKEN, payload: token }
          ]
        }),
        catchError(() => {
          return  of({ type: AuthenticationActions.LOGIN_FAILED })
        })
       )
     })
  );
  @Effect({dispatch: false})
  logout$ = this.actions$.ofType(AuthenticationActions.LOGOUT)
  .pipe(
    switchMap(()=>{
      this.router.navigate(['/logout']);
      return this.authenticationService.logout();
    })
  );

  constructor(
    private actions$: Actions,
    private router: Router,
    private authenticationService: AuthenticationService
  ) {}
}

reducer

export interface State {
  token: AuthenticationTokenInterface;
  authenticated: boolean;
  error: boolean;
}

const initialState: State = {
  token: null,
  authenticated: false,
  error: false
};

export function authenticationReducer(
  state = initialState,
  action: AuthenticationActions.AuthenticationActions
):State {
  switch (action.type) {
    case (AuthenticationActions.LOGIN_SUCCESS):
      return {
        ...state,
        authenticated: true,
      };
    case (AuthenticationActions.LOGIN_FAILED):
      return {
        ...state,
        error: true
      };
    case (AuthenticationActions.LOGOUT):
      return {
        ...state,
        token: null,
        authenticated: false
      };
    case (AuthenticationActions.SET_TOKEN):
      return {
        ...state,
        token: action.payload
      };
    default:
      return state;
  }
}

reducer (应用程序)

export interface AppState {
  authentication: fromAuthentication.State
}

export const reducers: ActionReducerMap<AppState> = {
  authentication: fromAuthentication.authenticationReducer
};

应用模块

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return localStorageSync({keys: ['authentication']})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

imports: [
  StoreModule.forRoot(
      reducers,
      {metaReducers}
  ),
  EffectsModule.forRoot([AuthenticationEffects]),
]

最佳答案

您需要将 rehydrate 键添加到 localStorageSync 函数调用。

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return localStorageSync(
     {keys: ['authentication'],
      rehydrate: true})(reducer);
}

参见:https://github.com/btroncone/ngrx-store-localstorage/blob/master/README.md了解详情。

关于angular ngrx-store-localstorage 在重新加载后不存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47581804/

相关文章:

angular - ng build --prod = 无法设置未定义的属性 '_autoActivated'

Angular 7,Reactive Form在有大数据时响应缓慢

redux - NGRX/Effects 将数据传递给 catchError

javascript - Nativescript( Angular )找不到用于延迟加载的模块

asp.net - 我如何绕过特定 url 的 "angular-in-memory-web-api"

python - 为什么我在使用 fabric 时会收到提示?

asp.net - 是否有相当于 IE 的 ClearAuthenticationCache 的浏览器?

php - 网站如何在不重新加载页面的情况下检查登录凭据?

angular - 如何调试 ngrx/store?

angular - NGRX Store adapter.updateone 不更改属性以进行更改检测