我正在设置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())
}
}
答案 0 :(得分:1)
您正在将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;
}
}