2017-01-30 93 views
3

我有一個應用程序,它需要分離已驗證和來賓用戶組件。但我需要,這兩個組件都將通過'/'路線加載。我寫了角度2具有相同路由的不同組件

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

它工作。但如何使這兩個組件加載相同的網址? 我曾嘗試爲成員的模塊路由寫入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/

我應該怎樣做正確?謝謝

+0

什麼是錯誤? – echonax

+0

對不起。沒有錯誤。但只執行第一個路由器規則 –

+0

如果沒有錯誤和第一個路由器規則滿足,那麼你的LoggedInGuard返回true? – echonax

回答

-1

這樣做的一種方法是根據用戶是否登錄路由到適當的區域。

(即是否打開空白的路線或客人的路線,它會被重定向適當和後退按鈕將無法正常工作)

路線:

{ 
    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; 
    } 
} 
+0

OP希望它們都具有相同的路由:「但是我需要,兩個組件都將通過'/'路由加載。」 – echonax

+0

@echonax您不能使用相同的路徑路徑加載不同的模塊(即使使用不同的警衛)。唯一的選擇是做類似上面的事情,不管打開哪條路徑,用戶都可以正確地重定向。 –

1

所以,我終於能夠做到這一點。 Angular使用第一個匹配策略,因此我們需要以守護式方式匹配路由,以確保與正確模塊匹配的正確路由。

我們需要爲我們的路線添加自定義matchers的第一件事,這些路線只會在我們想要的條件(例如用戶類型)上匹配它們。

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

而且匹配器的代碼是這樣的: 在這裏我注入AuthService服務從的AppModule,並檢查用戶鍵入它。所以路由可以根據用戶類型進行匹配。

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

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

現在只需要我們的東西是我們的主要模塊中創建applicationInjector,所以我們可以在我們的匹配功能注入服務;

export let applicationInjector: Injector; 

platformBrowserDynamic().bootstrapModule(AppModule).then((componentRef) => { 
    applicationInjector = componentRef.injector; 
}) 
相關問題