是否可以在指令中注入角度2路由器

时间:2016-07-11 17:01:45

标签: angular angular2-routing

我想在一个指令中注入angular 2路由器,该指令扩展了RouterOutlet我使用它而不是传统的插座来获得认证流程

@Directive({
    selector: 'router-outlet'
})
export class APPLICATION_ROUTER_DIRECTIVE extends RouterOutlet {
    constructor(parentOutletMap:RouterOutletMap, location:ViewContainerRef, componentFactoryResolver:ComponentFactoryResolver, name:string) {
        super(parentOutletMap, location, componentFactoryResolver, name);
    }

    activate(activatedRoute:ActivatedRoute, providers, outletMap) {
        let requiredUserRoles = activatedRoute.snapshot['_routeConfig'] ? activatedRoute.snapshot['_routeConfig'].roles : null;
        if (this.authorizeRoute(requiredUserRoles)) {
            return super.activate(activatedRoute, providers, outletMap);
        }
        else {
            let activeUserRole = AuthorizationService.getUserRole();
            switch (activeUserRole) {
                case null:
                case Role.ANONYMUS:
                case Role.USER: {
                    window.location.href = '/#';
                    break;
                }
                case Role.ADMIN: {
                    window.location.href = '/#/admin/users';
                    break;
                }
            }
        }
    }

    authorizeRoute(requiredRoles:Array<string>):boolean {
        let authorized = false;
        let activeUserRole = AuthorizationService.getUserRole();

        if (!requiredRoles) {
            requiredRoles = [Role.ANONYMUS, Role.USER];
        }

        if (!activeUserRole) {
            activeUserRole = Role.ANONYMUS;
        }

        return requiredRoles.indexOf(activeUserRole) !== -1;
    }

}

如果我注入路由器是未定义的,我希望从switch case导航到适当的页面,这是用户/管理员的默认值

1 个答案:

答案 0 :(得分:0)

You want routing that uses authentication. No injections and directive components don't really care (or know) about routing.

Look at the section called "Route Guards" and the CanActivate feature https://angular.io/docs/ts/latest/guide/router.html

BUT but the bigger question is, "Can you authorize in client side JS?" No, not really. You might have to think about how to move your authorization server side to make it truly secure.