I am trying to make a persistent login and everything works fine except if I am reload the page from the dashboard which is a page protected of AuthGuard I get redirected to login page but still I am logged in and also navbar works properly.Any suggestions would help me out a lot.
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); // this one returns false when I reload page
if (!res) {
this.router.navigate(['login']);
return false;
}
return true;
})
);
}
}
Below is my auth service
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'); // API server returns a boolean by calling req.isAuthenticated()-passport
}
}
I deleted unnecessary code but if you need anything more let me know and I will edit my post.
See Question&Answers more detail:os