I am working on an Angular app where I have a login page in my dashboard component. I am showing a set of data in my table component. I have successfully blocked the table route which the user cannot access until he has logged in. What I want to do is that after the user has logged in in the dashboard component, I want to block the dashboard component so that the user cannot access the login section again until he has logged out, which is my third component. I have tried doing that below but it's not working. Here's my code:
admin-layout.routing.ts
export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', canActivate: [RoleGuard], component: DashboardComponent },
{ path: 'user', component: UserComponent },
{ path: 'table', canActivate: [AuthGuard], component: TableComponent },
{ path: 'icons', component: IconsComponent }
];
auth-guard.service.ts //for the protection of my table component
constructor(private authService: AuthService, private router: Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
{
if(this.authService.isAuthenticated())
{
return true;
}
this.router.navigateByUrl('/dashboard');
return false;
}
role-guard.service.ts //for the protection of my dashboard component(login page)
constructor(private router: Router, private authService: AuthService){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
if(this.authService.isNotAuthenticated)
{
console.log("role guard True cond."); //this gets printed on console always, even after I login
return true;
}
console.log("role guard false cond.")
this.router.navigateByUrl('/table');
return false;
}
auth.service.ts //for defining the logic of the above two guards
export class AuthService
{
loggedIn:boolean = false;
check_Authentication(logIn : boolean)
{
if(logIn == true)
{
this.loggedIn = true;
}
else
{
this.loggedIn = false;
}
}
isAuthenticated()
{
if(this.loggedIn == true)
{
return true;
}
else
{
return false;
}
}
isNotAuthenticated()
{
if(this.loggedIn != true)
{
return true;
}
else
{
return false;
}
}
}
dashboard.component.ts //I am sending the variable as true if the user has logged in, here
private onAuthorization(form: NgForm)
{
this.http.post('http://localhost:3000/auth', form.value, {responseType: "text"})
.subscribe(responseData =>{
console.log(responseData);
if(responseData == "Successfully Authorized")
{
this.auth_check = true;
this.authService.check_Authentication(this.auth_check);
if(this.authService.isAuthenticated)
{
this.router.navigateByUrl('/table');
}
}
else
{
this.auth_failed = true;
}
}
,error => {
this.connectionToServer = false;
});
this.connectionToServer = true;
}
Can anybody tell me what am I doing wrong? EDIT: The login page isn't getting blocked after I navigate the user to the table page, which it should.