在包含路由器模塊v 3.0.0.6alpha的angular2 rc2中,我擴展了RouterOulet以在訪問管理員之前檢查用戶是否已登錄。所以這是代碼:Angular2 - 擴展路由器和Observable
@Directive({
selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet
{
publicRoutes: Array<string>;
private parentOutletMap: RouterOutletMap;
private userService: UserService;
private parentRouter: Router;
constructor(
parentOutletMap: RouterOutletMap,
_location: ViewContainerRef,
@Attribute('name') name: string,
userService: UserService,
parentRouter: Router
) {
super(parentOutletMap, _location, name);
this.parentRouter = parentRouter;
this.parentOutletMap = parentOutletMap;
this.userService = userService;
this.publicRoutes = [
'public',
'login'
];
}
activate(factory: ComponentFactory<any>, activatedRoute: ActivatedRoute, providers: ResolvedReflectiveProvider[], outletMap: RouterOutletMap)
{
if (this._canActivate(factory.selector)) {
return super.activate(factory, activatedRoute, providers, outletMap);
}
this.parentRouter.navigate(['/login']);
}
_canActivate(url) {
return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn()
}
}
userService.isLoggedIn()必須返回一個布爾值。我的問題是:如何調整我的代碼以進行http調用以檢查用戶是否已登錄?因爲如果isLoggedIn方法返回一個可觀察對象,並且我訂閱了它,我不能在父函數中返回結果。
似乎不錯,謝謝!但我不知道在哪裏注射這名後衛?如果你可以編輯你的代碼來顯示它... –
發佈原始答案後,我做了幾分鐘;)我忘了添加此之前。 – Baumi
整潔!再次感謝 –