I recently encountered an issue while working on my Angular 11 project. Everything was running smoothly until I faced the following problem:
When using routerlink to navigate to a specific path, it redirects correctly. However, if I attempt to access that path manually by entering "localhost:4200/reunion" in the browser, it initially redirects to an empty path and then redirects to the home page at "localhost:4200/tableau_de_bord".
Below is a snippet of my app.routing.ts file:
const routes: Routes = [
{
path: 'connexion',
component: ConnexionComponent
},
// ... other paths
{
path: '',
redirectTo: 'tableau_de_bord',
pathMatch: 'full',
canActivate: [AuthGuard],
},
// ... other paths
];
@NgModule({
imports: [
CommonModule,
BrowserModule,
RouterModule.forRoot(routes)
],
})
export class AppRoutingModule { }
This is what my admin-layout.routing.ts looks like:
export const AdminLayoutRoutes: Routes = [
{ path: "", redirectTo: "tableau_de_bord", pathMatch: "prefix" },
{ path: "tableau_de_bord", component: DashboardComponent },
{
path: "reunion",
component: ListReunionComponent,
canActivate: [AuthGuard],
},
// ... other routes
];
And here is my admin-layout.module.ts:
@NgModule({
imports: [
// ... other imports
RouterModule.forChild(AdminLayoutRoutes),
// ... other imports
],
})
export class AdminLayoutModule { }
The main issue I'm facing is with refreshing or reloading the page and ending up at the correct path. Accessing paths defined in app.routing.ts works fine, but when trying paths from admin-layout.ts like "localhost:4200/reunion", it redirects back to the homepage "localhost:4200/tableau_de_bord". Even after removing canActivate from both routing files, the issue persists.
I also tested this scenario in private browsing mode without success. One thing worth mentioning is that I had "
Update: Here is the AuthGuard code being used:
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
public url:any;
constructor(private router: Router,private authService: AuthServiceService) {}
canActivate( next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
let url: string = state.url;
return this.checkUserLogin(next, url);
}
checkUserLogin(route: ActivatedRouteSnapshot, url: any): boolean | UrlTree {
if (this.authService.isLoggedIn()) {
const userRole = this.authService.getRole();
if (route.data.role && route.data.role.indexOf(userRole) === -1) {
this.router.navigate(['/connexion']);
return false;
}
return true;
}
this.url = url;
this.router.navigate(['/connexion']);
return false;
}
}