首页 > 解决方案 > 身份验证服务用户为空

问题描述

我正在设置route guard将经过身份验证的用户与来宾分开。我写了一个auth-guard service和一个auth service。用户数据正在本地存储中设置,但console.log()打印usernull.

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())
  }
}

标签: angulartypescriptasynchronous

解决方案


您正在注入Storageas 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;
  }
}

推荐阅读