Ответ 1
Итак, документация похожа на то, что она экспортирует.
export CanActivate(options : CanActivateAnnotation) : (hook: (next: ComponentInstruction, prev: ComponentInstruction) =>
Promise<boolean>| boolean) => ClassDecorator
@CanActivate((next, prev) => {
// This must prove to be true for the component @ this route to load
if(next.urlPath != '/Login'){
return Promise.resolve(this._authService.getIsAuth()
&& localStorage.getItem('authToken')
}
/*
If CanActivate returns or resolves to false, the navigation is
cancelled. If CanActivate throws or rejects, the navigation is also
cancelled. If CanActivate returns or resolves to true, navigation
continues, the component is instantiated, and the OnActivate hook of
that component is called if implemented.
*/
}
);
В нижней части документа Angular2 добавлен этот фрагмент: экспортируется из angular2/router https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html
Итак, если вы хотите перенаправлять с более высокого уровня. Вы бы не использовали декоратор CanActivate, вы бы сделали следующее.
import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
import {Login} from '../login/login';
import {UserService} from '../../Services/userService'; // a service to handle auth
@Directive({
selector: 'router-outlet'
})
export class AuthRouterOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
constructor(private _userService:UserService, _elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, @Attribute('name') nameAttr: string) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
this.publicRoutes = {
'/login': true,
'/signup': true
};
// publicRoutes will be the routes auth is not needed for.
}
activate(instruction: ComponentInstruction) {
var url = this.parentRouter.lastNavigationAttempt;
if (!this.publicRoutes[url] && this._userService.getAuth()) {
// todo: redirect to Login, may be there a better way?
this.parentRouter.navigateByUrl('/login');
}
return super.activate(instruction);
// we return super.activate(instruction) here so the router can activate the requested route and it components.
}
}
Эта реализация обрабатывает любой новый запрос директивы и запускает функцию активации, где будет логика проверки маршрута. Вышеупомянутый код будет называться чем-то вроде AuthRouterOutlet. и вы должны добавить его в свой app.ts через
directives: [ AuthRouterOutlet]