【问题标题】:Is it possible to inject angular 2 router in directive是否可以在指令中注入 angular 2 路由器
【发布时间】:2016-07-11 17:01:45
【问题描述】:

我想在扩展 RouterOutlet 的指令中注入 angular 2 路由器,我使用它而不是传统的出口来进行身份验证流程

@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 导航到正确的页面,这些页面是用户/管理员的默认页面

【问题讨论】:

  • 是否可以注入路由器或者我应该只使用页面的刷新?

标签: angular angular2-routing


【解决方案1】:

您想要使用身份验证的路由。没有注入和指令组件并不真正关心(或知道)路由。

查看名为“Route Guards”的部分和 CanActivate 功能 https://angular.io/docs/ts/latest/guide/router.html

但更大的问题是,“你能在客户端 JS 中授权吗?”不,不是。您可能需要考虑如何移动授权服务器端以使其真正安全。

【讨论】:

  • 我同意将其更改为服务器检查,但我想将所有身份验证移动到路由器,因此我可以捕获激活并从那里重定向到不写可以重新激活,更像是一个过滤器
猜你喜欢
  • 2017-01-01
  • 2017-10-05
  • 2012-07-24
  • 2016-06-10
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多