Currently, I am facing an issue with my persistent login functionality. Everything seems to be working fine except when I reload the page from a protected dashboard that requires AuthGuard. Upon reloading, I get redirected to the login page even though I am still logged in and the navbar functions properly. Any suggestions or solutions would be greatly appreciated.
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.getLoggedIn
.pipe(
map((res: boolean) => {
console.log(res); // It returns false when I reload the page
if (!res) {
this.router.navigate(['login']);
return false;
}
return true;
})
);
}
}
Below is my authentication service code:
export class AuthService {
private loggedIn: BehaviorSubject<boolean>;
constructor(private http: HttpClient) {
this.loggedIn = new BehaviorSubject<boolean>(false);
}
setLoggedIn(value: boolean) {
this.loggedIn.next(value);
}
get getLoggedIn() {
this.updatelogin().subscribe(res => {
this.loggedIn.next(res);
})
return this.loggedIn.asObservable();
}
updatelogin() {
return this.http.get<boolean>('/api/islogged'); // An API call to check if user is authenticated
}
}
I have removed some unnecessary code for clarity, but feel free to ask if you need more information.