Currently, I have implemented a guard in my app to secure certain routes. The guard relies on a session service to extract credentials from localStorage during NgOnInit. The goal is for the guard to check with the session service for valid credentials before allowing access to protected routes.
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { SessionService } from './../session/session.service'
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private sessionService: SessionService
) { }
canActivate() {
// Ensure user data is loaded
//this.sessionService.loadUser();
if (this.sessionService.isValidSession()) {
return true;
}
// Redirect to login page if not logged in
this.router.navigate(['/login']);
return false;
}
}
Here is a snippet of my session service:
export class SessionService implements OnInit {
.
.
.
constructor(
private authService: AuthenticationService,
) {
this.timeout = null;
}
ngOnInit() {
this.loadUser();
}
The issue I'm facing is that the ngOnInit method in the session service does not execute automatically. Instead, I have to manually call loadUser() within the guard. How can I ensure that the ngOnInit of the session service runs before the canActivate method of the guard?
Thank you for any suggestions or solutions!