I am working on an Angular app where I am using the following structure:
- app
layouts
- admin-layout
pages
- dashboard
- icons
- table
- user
shared
sidebar
I am trying to write auth-guard.service.ts and auth.service.ts in admin-layout as I have defined my routing there for the pages that I want to access on DOM.
However, when I try to login in dashboard page it doesn't navigate to the route that I have written in the code. But, when I click on the route on the sidebar it only prints the variable as true which is what the auth-guard here does. It doesn't navigate to that route. Here is my code:
admin-layout.routing.ts
export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'user', component: UserComponent },
{ path: 'table', canActivate: [AuthGuard], component: TableComponent },
{ path: 'icons', component: IconsComponent }
];
auth-guard.service.ts
constructor(private authService: AuthService, private router: Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> |
Promise<boolean> | boolean
{
return this.authService.isAuthenticated().then(
(authenticated: boolean) => {
if(authenticated){
console.log('accessed this if part');
this.router.navigate(["/table"]); // isn't navigating to this
}
else
{
console.log("Accessed else part");
return false;
}
}
)
}
auth.service.ts
export class AuthService
{
loggedIn:boolean;
isAuthenticated()
{
const promise = new Promise((resolve, reject) =>{
setTimeout(() => {
resolve(this.loggedIn);
}, 100);
}
);
return promise;
}
check_Authentication(logIn : boolean)
{
if(logIn == true)
{
this.loggedIn = true;
}
}
}
dashboard.component.ts
constructor(private http: HttpClient, private router: Router, private authService: AuthService){}
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);
}
else
{
this.auth_failed = true;
}
}
Any idea what am I doing wrong here? Edit: When I try to access the route by clicking on the table on my sidebar then an infinite loop starts printing the same thing.
You can use child components as follows