我正在开发一个 Angular 应用程序,它具有以下URL路径,
- /(根目录)
- /类(class)
- /类(class)/创建
- /类(class)/:id
- /验证/登录
我已为除 auth/login
之外的所有路由添加了 AuthGuard。如果未经过身份验证,AuthGuard
会重定向到 auth\login
。
app-routing.module.ts
export const Approutes: Routes = [
{
path: '',
canActivate: [AuthGuard],
component: FullComponent,
loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) // loading from pages-routing.ts
},
{
path: 'auth',
component: PlainComponent,
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'login'
},
{
path: 'login',
component: LoginComponent
}
]
},
{
path: '**',
redirectTo: ''
}
];
pages-routing.ts
export const PagesRoutes: Routes = [
{
path: '',
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'courses'
},
{
path: 'courses',
component: CourseMainPageComponent,
data: {
title: 'My Courses'
}
},
{
path: 'courses/create',
component: CourseCreatePageComponent,
data: {
title: 'Create Course'
}
},
{
path: 'courses/:id',
component: CourseShowPageComponent,
data: {
title: 'Course Detail'
}
},
]
}
];
问题
所有路由和 authGuard 工作正常。 但是当我输入根URL \
时,我需要重定向到\courses
,但它不起作用。 此外在根 URL \
中 AuthGuard 甚至没有将我重定向到到auth\login
。
NOTE I don't get any run-time or compile error.
最佳答案
您需要更改 pathMatch在您用于重定向的路由中将策略设置为 full
。根据文档,
The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.
您的路线配置现在看起来像这样
export const PagesRoutes: Routes = [{
path: '',
children: [{
path: '',
redirectTo: 'courses',
pathMatch: 'full'
},
// Add other routes here
]
}];
关于javascript - AuthGuard 和 RedirectTo 不适用于根路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438187/