I have been searching in order to avoid duplicated posting etc. and did give some solutions a try, but was not successful to fix the issue.
I use canActivate to protect a dashboard and it works fine except that it always returning false so that I can never access the protected routers.
I don't get any error or something similar so that I can localize and fix.
the isAuthenticated
is always being set to false and doesn't get the result of the function: setAuthenticated()
which is changing it to: true
.
Any idea please?
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;
}
}