我在Angular 4中有一个Guard,但是当我尝试访问受保护的路由时,浏览器显示此错误:
NodeInvocationException: Uncaught (in promise): ReferenceError: localStorage is not defined
这是我的守卫:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from "rxjs/Observable";
@Injectable()
export class ProtectGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.warn("validando");
if (localStorage.getItem('ex-token'))
return true;
this.router.navigate(['/login']);
return false;
}
}
我不知道是什么原因造成的,谢谢。
答案 0 :(得分:0)
这很奇怪。您是否可以通过其他服务访问localStorage中的项目?我在想的是一种代理服务。这只是数字刮痕:
LocalStorageService
setItem(item: any, key: string): void {
localStorage.setItem(key, item);
}
getItem(key: string): any {
return localStorage.getItem(key);
}
您的后卫
constructor (private localStorageService: LocalStorageService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.warn("validando");
if (this.localStorageService.getItem('ex-token'))
return true;
...
也许这做对了。仍然无法解释为什么您的服务无法访问localStorage。