验证服务用户为空

时间:2019-08-09 08:41:53

标签: angular typescript asynchronous

我正在设置route guard,以将经过身份验证的用户与来宾分开。我写了auth-guard serviceauth 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())
  }
}

1 个答案:

答案 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;
  }
}