【问题标题】:localStorage is not defined when call to tokenNotExpired调用 tokenNotExpired 时未定义 localStorage
【发布时间】:2018-10-10 16:38:40
【问题描述】:

我想将 angular2-jwt 集成到我的项目中:https://github.com/auth0/angular2-jwt

当我尝试调用函数 tokenNotExpired 时,我得到了这个异常:

异常:调用节点模块失败并出现错误:ReferenceError: 在 Object.tokenNotExpired 中未定义 localStorage

这是我的代码:

auth.service.ts

import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class Auth {

    loggedIn() {
        return tokenNotExpired();
    }

}

app.component.ts

import { Component } from '@angular/core';
import { Auth } from '../.././services/auth.service';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private auth: Auth) { }
}

app.component.html

<div class='container-fluid'>
    <div class='row'>
        <div *ngIf="auth.loggedIn()" class='col-sm-3'>
            <nav-menu></nav-menu>
        </div>
        <div class='col-sm-9 body-content'>
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

谢谢

【问题讨论】:

    标签: javascript angular local-storage angular-universal angular2-jwt


    【解决方案1】:

    我找到了解决方案。问题是 angular-universal 在客户端和服务器端执行代码。并且在服务器端“窗口”对象不存在。

    防止代码在服务器端运行:

    loggedIn() {
            if (typeof window !== 'undefined') {
                return tokenNotExpired();
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2021-03-18
      • 2018-08-21
      • 2021-10-17
      • 2016-12-29
      • 2015-04-18
      • 2015-10-14
      • 2022-10-31
      • 2011-11-17
      相关资源
      最近更新 更多