例如,如果用户通过身份验证,URL:www.example.com 应该加载一个模块,否则它应该加载另一个模块。
我试过使用守卫,但它没有像我期望的那样工作。
我对 Angular 很陌生。如果有人可以编写示例路由数组进行演示,将不胜感激。:)
如果用户未通过身份验证,我希望我的路线如下所示:
{
path: '',
loadChildren: './home/home.module#HomeModule'
},
{
path: 'login',
loadChildren: './login/login.module#LoginModule'
},
{
path: 'register',
loadChildren: './register/register.module#RegisterModule'
}
否则,如果用户已通过身份验证,我希望我的路线如下所示:
{
path: '',
pathMatch: 'full',
redirectTo: '/dashboard'
},
{
path: 'dashboard',
loadChildren: './dashboard/dashboard.module#DashboardModule'
},
{
path: 'profile',
loadChildren: './user-profile/user-profile.module#UserProfileModule'
}
是的,您可以使用CanActivate
警卫(检查路线访问)来实现这一点。
CanActivate
检查用户是否可以访问路由。
话虽如此,我希望您在guardCheck
.
您不应该让路由器配置在同一路由上容纳两个不同的组件或模块。您可以将它们添加为路线的子项,并在同一路线上需要它们时决定路线。
更新:
我遇到了matcher
可以用来在同一路径上加载两条不同路由的概念:
const routes: Routes = [{
path: 'list',
matcher: matcherForAuthenticatedRoute,
loadChildren: './user/register#RegisterModule'
},
{
path: 'list',
matcher: matcherForTheOtherRoute,
loadChildren: './user/home#HomeModule'
}]
现在我们的匹配逻辑依赖于两个函数,如下所示:
export function matcherForAuthenticatedRoute(
segments: UrlSegment[],
group: UrlSegmentGroup,
route: Route) {
const userService = appInjector.get(MyService);
const isPathMatch = segments[0].path === route.path;
const isUserAuthenticated = userService.isUserAuthenticated('userId');
if(isPathMatch && isUserTypeMatch) {
return {consumed: [segments[0]]};
} else {
return null;
}
}
我们可以appInjector
在引导应用程序后定义并将其导出以供使用:
appInjector = componentRef.injector;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句