Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

angular2 routing - Angular 2 different components with same route

I have an application, which need to separate authenticated and guest users components. But I need, that both components will be loaded by '/' route. I wrote

{
    path: 'desktop',
    loadChildren: 'app/member/member.module#MemberModule',
    canActivate: [LoggedInGuard],
},
{
    path: '',
    loadChildren: 'app/guest/guest.module#GuestModule',
    canActivate: [GuestGuard],
},

And it works. But how to make, that both component load by same url? I had tried to write path: '' for Member's module route, but the second router rule is not performed. Here are guards code:

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;
    }
}

Here is a plunker: http://embed.plnkr.co/VaiibEVGE79QU8toWSg6/

How should I do it properly? Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So i was finally able to do this. The thing is Angular uses first match policy, so we need to match routes in a guard-type way, to be sure that right route with right module will be matched.

First thing we need to add custom matchers for our routes which will only match them on conditions that we want (user type for example).

{
 path: 'samePath',
 matcher: firstMatcher,
 loadChildren: '../first/first.module#FirstModule'
},
{
 path: 'samePath',
 matcher: secondMatcher,
 loadChildren: '../second/second.module#SecondModule'
}

And matchers code is something like this: In here i injected AuthService service from AppModule, and checked users type with it. So routes can be matched according to users type.

import { applicationInjector } from '../../main';

export function firstMatcher (url: UrlSegment[]) {
  const auth =  applicationInjector.get(AuthService);
  return auth.isUserType('admin') ? ({consumed: [url[0]]}) : null;
}

And now only thing we need is to create applicationInjector in our main module, so we could inject service in our matcher-function;

export let applicationInjector: Injector;

platformBrowserDynamic().bootstrapModule(AppModule).then((componentRef) => {
  applicationInjector = componentRef.injector;
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...