У меня есть приложение angular 2, в котором мне нужно пройти аутентификацию на каждой странице. Поэтому я реализовал собственный RouterOutlet, чтобы подтвердить, что я вхожу в систему при каждом изменении страницы.
@Directive({
selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
private authService: AuthService;
constructor(_elementRef: ElementRef,
_loader: DynamicComponentLoader,
_parentRouter: Router,
@Attribute('name') nameAttr: string,
_authService: AuthService) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
this.authService = _authService;
this.publicRoutes = {
'Login': true
};
}
activate(oldInstruction: ComponentInstruction) {
var url = this.parentRouter.lastNavigationAttempt;
console.log('attemping to nav');
if (!this.publicRoutes[url] && !this.authService.loggedIn){
var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
return super.activate(newInstruction);
} else {
return super.activate(oldInstruction);
}
}
}
Вот рабочий код: http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=preview
Есть ли лучший способ перехватить изменения маршрута и перенаправить для входа в систему, когда пользователь не аутентифицирован?
var url = this.parentRouter.lastNavigationAttempt
, в URL?? - person micronyks   schedule 24.02.2016