angular - 身份验证服务用户为空
问题描述
我正在设置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())
}
}
解决方案
您正在注入Storage
as 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;
}
}
推荐阅读
- c# - 如何在 RazorEngine 中使用命名空间辅助函数?
- android - Galaxy S9 设备在模拟时一直显示为“离线”
- c# - 无法在 .NET Core 中获取自定义应用设置的价值
- terraform - 如何在顶层和模块之外嵌套 Terraform 堆栈
- java - 如何使用 Spring Data Mongo Mapper 和复合键指定键参数顺序
- c - 将一个指针数组连接并添加到另一个指针数组的一个索引中
- sql - 如何拆分SQL中每一行的数字?
- java - 非法块大小异常 解密时使用填充密码解密时输入长度必须是 16 的倍数
- c++ - EXEC BAD ACCESS 遍历向量
- python - 如何使用 Python + Numpy 获得组中的变异系数?