保护多个Angular 2组件的好方法 [英] Good way to secure multiple Angular 2 components

查看:124
本文介绍了保护多个Angular 2组件的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐的保护Angular 2组件/路由的常用方法似乎是使用@CanActivate(),如下所示:

A common recommended way to secure Angular 2 component/routes seems to be to use @CanActivate(), like here:

http://youknowriad.github.io/angular2-cookbooks/stateless- authentication.html

如果只有几个组件,则可以很好地工作,但是有没有更好的方法来集中所有这些呢?

If you have only a few components this works fine, but is there a better way that would centralize all this?

每个组件都有一个通用的基类吗? (有关如何执行此操作的任何示例?).我们可以有一个自定义的@CanActivate(),例如@ProtectMyApp()吗? (例如?)

Would having a common base class for each component work? (any examples on how to do this?). Could we have a custom @CanActivate(), something like @ProtectMyApp()? (examples?)

我基本上是在尝试避免必须为每个组件复制并粘贴相同的@CanActivate()代码.

I'm basically trying to prevent having to copy+paste the same @CanActivate() code for each component.

(抱歉,如果这些问题没有道理,请继续学习Angular)

(apologies if these questions do not make sense, still learning Angular)

谢谢

推荐答案

您可以创建一个全局回调,并将其传递给@CanActivate装饰器:

You can create a global callback that you can pass into the @CanActivate decorator:

export function isAllowed(): boolean | Promise<boolean>{
    // Permission logic here
}

然后您可以将该函数传递给装饰器

and then you can pass that function into the decorator

@Component({...})
@CanActivate(isAllowed)
export class MyComponent{

}

这将为您提供验证权限的全局来源,但仍将使用内置方法.

This would give you a global source of validating permission, but still use the built in methods.

更新

这未经测试,但可以用于将服务注入isAllowed

在文档中,我发现bootstrap方法返回的ComponentRef具有injector属性,该属性在文档中具有以下注释

In the documentation I found that the bootstrap method returns a ComponentRef which has an injector property that has the following comment in the docs

注入器提供了DynamicComponentLoader.

The injector provided DynamicComponentLoader.

这可能是获得与主注射器用于该应用程序相同的单例实例的黄金票.从理论上讲,这应该起作用

This could be the golden ticket for getting the same singleton instance that is used by the main injector for the application. In theory this should work

在您的启动文件中

export var applicationInjector: Injector;
bootstrap(AppComponent, [MyService, ...]).then((ref: ComponentRef) => {
    applicationInjector = ref.injector;
});

然后使用isAllowed方法在文件中

Then in the file with your isAllowed method

import {applicationInjector} from '...';

export function isAllowed(): boolean | Promise<boolean>{
    let myService: MyService = applicationInjector.get(MyService);
    return myService.isAllowed();
}

这篇关于保护多个Angular 2组件的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆