我有一个应用程序,需要分离经过身份验证的和来宾用户组件。但我需要,两个组件都将通过'/'路由加载。我写
{
path: 'desktop',
loadChildren: 'app/member/member.module#MemberModule',
canActivate: [LoggedInGuard],
},
{
path: '',
loadChildren: 'app/guest/guest.module#GuestModule',
canActivate: [GuestGuard],
},
它有效。但是如何制作,两个组件加载相同的URL?我曾尝试为成员的模块路由编写path: ''
,但是没有执行第二个路由器规则。这是卫兵代码:
LoggedInGuard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this.sessionService.isLoggedIn()) {
return true;
} else {
return false;
}
}
GuestGuard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(!this.sessionService.isLoggedIn()) {
return true;
} else {
return false;
}
}
这是一个plunker:http://embed.plnkr.co/VaiibEVGE79QU8toWSg6/
我该怎么做呢?谢谢
所以我终于能够做到这一点。问题是Angular使用第一个匹配策略,因此我们需要以保护类型的方式匹配路由,以确保匹配正确模块的正确路由。
首先我们需要为我们的路线添加自定义matchers,它们只会在我们想要的条件下匹配它们(例如用户类型)。
{
path: 'samePath',
matcher: firstMatcher,
loadChildren: '../first/first.module#FirstModule'
},
{
path: 'samePath',
matcher: secondMatcher,
loadChildren: '../second/second.module#SecondModule'
}
并且匹配器代码是这样的:在这里我从AppModule注入了AuthService服务,并检查用户输入它。因此可以根据用户类型匹配路由。
import { applicationInjector } from '../../main';
export function firstMatcher (url: UrlSegment[]) {
const auth = applicationInjector.get(AuthService);
return auth.isUserType('admin') ? ({consumed: [url[0]]}) : null;
}
现在我们只需要在主模块中创建applicationInjector
,这样我们就可以在matcher函数中注入服务;
export let applicationInjector: Injector;
platformBrowserDynamic().bootstrapModule(AppModule).then((componentRef) => {
applicationInjector = componentRef.injector;
})
一种方法是根据用户是否登录来路由到适当的区域。
(即,您是打开空白路线还是客人路线,它将被适当地重定向,并且后退按钮将不起作用)
路线:
{
path: '',
loadChildren: 'app/member/member.module#MemberModule',
canActivate: [LoggedInGuard],
},
{
path: 'guest',
loadChildren: 'app/guest/guest.module#GuestModule',
canActivate: [GuestGuard],
}
LoggedInGuard ::
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this.sessionService.isLoggedIn()) {
return true;
} else {
// route to 'guest' if not logged in
this.router.navigate(['/guest'], { replaceUrl: true });
return false;
}
}
GuestGuard(如果已登录,则自动路由到MemberComponent):
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this.sessionService.isLoggedIn()) {
// route to member area if already logged in
this.router.navigate(['/'], { replaceUrl: true });
return false;
} else {
return true;
}
}