我将route guard设置为将经过身份验证的用户与来宾分开。我写了一个auth-guard service和一个auth service。用户数据正在本地存储中设置,但console.log()将user打印为null。
auth.service.ts
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(public storage: Storage) {}
// ...
public isAuthenticated(): boolean{
const user: any = localStorage.getItem('user');
console.log(user); // null in console
if (user !== null
&& user.token !== null
&& user.token_deadline !== null
&& new Date(user.token_deadline) > new Date())
return true;
return false;
}
}auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service'
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private router: Router, private authService: AuthService) {
}
canActivate(route: ActivatedRouteSnapshot): boolean {
return(this.authService.isAuthenticated())
}
}发布于 2019-08-09 08:48:54
您将Storage注入为storage,但在您的方法中您正在调用localStorage。这似乎不对。不是应该是this.storage吗?
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(public storage: Storage) {}
// ...
public isAuthenticated(): boolean{
const user: any = this.storage.getItem('user'); // <-- here
console.log(user); // null in console
if (user !== null
&& user.token !== null
&& user.token_deadline !== null
&& new Date(user.token_deadline) > new Date())
return true;
return false;
}
}https://stackoverflow.com/questions/57426393
复制相似问题