调用 tokenNotExpired 时未定义 localStorage

localStorage is not defined when call to tokenNotExpired

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

当我尝试调用函数 tokenNotExpired 时出现此异常:

Exception: Call to Node module failed with error: ReferenceError: localStorage is not defined at Object.tokenNotExpired

这是我的代码:

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>

谢谢

我找到了解决办法。问题是 angular-universal 在客户端和服务器端执行代码。在服务器端 'window' 对象不存在。

防止 运行 在 server-side 上的代码:

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