【问题标题】:Clear localStorage on every refresh in angular 2在角度 2 中每次刷新时清除 localStorage
【发布时间】:2017-06-08 17:30:08
【问题描述】:

身份验证后我将令牌存储在 localStorage 中,但每次刷新时我都需要将其删除并重定向到某个路由器。

我不知道如何在 Angular 中做到这一点。我正在使用纯js的一种非常hacky的方式。

window.addEventListener('load', function (e) {
  if (window.sessionStorage !== null && (window.location.href.indexOf('/signin') === -1 &&  window.location.href.indexOf('confirm-user') === -1)) {
    window.sessionStorage.clear();
    window.location.href = '/signin';
  }
});

我正在考虑添加一个身份验证保护,但我确信应该有一种更角度的方式来做到这一点。

【问题讨论】:

  • 如果您有一个不想在页面重新加载后幸存下来的值(假设这就是您所说的“进行刷新”) - 那么您为什么首先将它放入 localstorage ……?一个普通的普通 JavaScript variable 可以实现这一点,而无需执行任何额外的步骤...

标签: angular angular-routing angular-router-guards


【解决方案1】:

我建议创建一些身份验证服务来将您的令牌存储为一个普通变量和一个Guard,以防止重定向到没有令牌的安全页面。您可以在一项服务中实现它:

@Injectable()
export class AuthService implements CanActivate, CanActivateChild {
    token:String;
    canActivateChild = this.canActivate;
    constructor(private router: Router) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (!this.token) {
            this.router.navigate(['/signin']);
            return false;
        }
        return true;
    }
}

export const ROUTES: Routes = [{
    path: 'signup',
    component: SignupComponent
}, {
    path: 'securedpath',
    component: SecuredComponent,
    canActivateChild: [AuthService],
    canActivate: [AuthService]
}]

但是这个服务应该是单例的。记在心上。在你的 app.module 的提供者列表中声明它(或者 core.module 如果你使用 Jonh Papa 的风格指南)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多