What could be the reason that I don't see any paths in the browser but only localhost:4200 . But I can navigate normally through the application. My routing.ts looks like this.
I use Angular 12
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { VacComponent } from './modules/vac/vac.component';
import { VibComponent } from './modules/vib/vib.component';
import { CatComponent } from './modules/cat/cat.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{ path: '', redirectTo: 'login'},
{
path: 'login',
component: LoginComponent
},
{
path: 'dashboard',
component: DashboardComponent,
// canActivate: [AuthGuard]
},
{
path: 'vac',
component: VacComponent,
loadChildren: () => import('./modules/vac/vac.module').then(m => m.VacModule),
// canActivate: [AuthGuard]
},
{
path: 'vib',
component: VibComponent,
loadChildren: () => import('./modules/vib/vib.module').then(m => m.VibModule),
// canActivate: [AuthGuard]
},
{
path: 'cat',
component: CatComponent,
loadChildren: () => import('./modules/cat/cat.module').then(m => m.CatModule),
// canActivate: [AuthGuard]
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
CodePudding user response:
I tried reproducing your error in a Stackblitz without success. Here is the link. What I found strange in your example is that you don't specify a pathMatch to your first redirect. I think that might be the issue.
CodePudding user response:
By default, the Angular compiler matches routes by a prefix. Therefore the route { path: '', redirectTo: 'login'}
will match all the subsequent routes in the routes
array.
Also since the default route matching strategy is set to prefix
, which basically indicates that the Angular Router
will route on the basis of the path that matches with the prefix of the URL you are navigating to. And as every path starts with '' all the redirects navigates the user to /login
component.
Therefore, to resolve this issue you need to explicitly change the route matching strategy to full
.
const routes: Routes = [{
path: '',
redirectTo: '/login',
pathMatch: 'full'
},
...,
...,
];
As pathMatch: full
indicates that the entirety of the URL path needs to be matched for the Angular Router to route, user to the directed path.
Or,
Move the route definition with pathMatch: prefix
to the bottom of the routes
array as shown in the following snippet.
const routes: Routes = [
...,
...,
...,
{
path: '',
redirectTo: '/login',
pathMatch: 'prefix'
}
]