I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue.
My implementation of canActivate to secure a dashboard seems to be working properly, but it's always returning false, preventing me from accessing the protected routes.
There are no error messages or indications that could help me pinpoint and fix the problem. The isAuthenticated
flag remains false despite calling the setAuthenticated()
function to set it to true.
Any suggestions on how to address this?
auth.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AuthService {
public isAuthenticated = false;
constructor(private http: HttpClient) {
}
setUserLoggedIn() {
this.isAuthenticated = true;
}
getUserLoggedIn() {
return this.isAuthenticated;
}
public setAuthenticated() {
this.http
.get<any>(url, {withCredentials: true, observe: 'response'})
.subscribe(
(res) => {
console.log('Status: Authenticated: ' + res.headers.get('status') );
if ( res.headers.get('status') === '200') {
this.setUserLoggedIn();
}
},
err => {});
}
}
authguard.guard.ts
:
import { Injectable } from '@angular/core';
import { CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router,
ActivatedRoute} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { AuthService } from './service/auth.service';
@Injectable()
export class AuthguardGuard implements CanActivate {
constructor(
private user: AuthService,
public router: Router,
private http: HttpClient,
private activatedRoute: ActivatedRoute) {
}
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if ( !this.user.isAuthenticated ) {
console.log('Not authenticated!');
this.router.navigate(['userLogin']);
return false;
}
return true;
}
}