I have an application with login page and dashboard. I have used AuthGuard to redirect the routeto dashboard only if token exists and valid. But when I enter URL /login it goes back to login page even if the token exists.
This is my code which I have tried;
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router,
} from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthenticationService } from './authentication.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthenticationService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable<boolean> | Promise<boolean> {
const isAuth = this.authService.getIsAuth();
if (!isAuth) {
this.router.navigate(['/login']);
}
return isAuth;
}
}
app routing module
{ path: '',
canActivate: [AuthGuard],
component: dashboard
},
{ path: 'signin',
component: signin
}
authService: Here i'm setting my isAuthenticated to false and enabling it to true when i get the access_token
private isAuthenticated = false;
getIsAuth() {
return this.isAuthenticated;
}
return this.http.post(api, data)
.subscribe(
(response) => {
if (response && response.access_token) {
console.log(response.access_token);
this.isAuthenticated = true;
.......
}
})
getIsAuthlook like?signinpath, so a user will always be able to navigate to it. You could develop a route guard which only allows for unauthenticated users, and have it redirect the user to the dashboard route if they're already logged in.