Currently, I am working on implementing a route guard
to distinguish between authenticated users and guests. In order to achieve this, I have created an auth-guard service
along with an auth service
. Although the user data is successfully stored in the local storage, when I use console.log()
to print out the user
object, it displays as 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())
}
}