I have encountered a strange issue while developing my angular app which involves the router functionality. All routes were working perfectly fine until I discovered that after a successful login, instead of navigating to the '/admin' path as intended, the router defaults back to '/' for some reason. Here is the relevant code snippet:
//login.component.ts
if (this.authService.getUserRole() == 'user' || this.authService.getUserRole() == 'agent') {
window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
window.location.assign('/admin')
}
//app.routing.ts
import {AdminComponent} from './admin-master/admin/admin.component;
import {HomeComponent} from './home/home.component;
const appRoutes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: {permission:{only: ['admin']}}}
]
EDIT: (added auth.guard.ts)
//auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const permission = next.data["permission"];
if(this.authService.isLoggedIn() &&
permission.only.includes(this.authService.getUserRole())) {
return true;
} else {
this.router.navigateByUrl('/logout');
}
}
}
The Issue:
Despite a successful login, the router redirects users to an empty URL instead of the specified URL set in the
login.component.ts
file.This leads to elements from the
home.component.html
being displayed in the admin dashboard, which should not be happening.
In summary, how can I ensure the routing functions correctly? Is there an error in my approach? Thank you for your assistance!