保护多个Angular 2组件的好方法

时间:2016-02-04 01:18:27

标签: angular

保护Angular 2组件/路由的常用建议方法似乎是使用text_content(),如下所示:

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

如果你只有几个组件,这可以正常工作,但有没有更好的方法可以集中所有这些?

每个组件的公共基类是否有效? (有关如何执行此操作的任何示例?)。我们可以使用自定义from lxml.html import fromstring data = """ <tr> <td>a</td> <td>a</td> <td>b</td> <td></td> <td>b</td> </tr>""" tree = fromstring(data) for td in tree.xpath(".//td"): print(td.text_content()) ,例如a a b b 吗? (实施例?)

我基本上试图阻止为每个组件复制+粘贴相同的@CanActivate()代码。

(道歉,如果这些问题没有意义,仍在学习Angular)

由于

1 个答案:

答案 0 :(得分:5)

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

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

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

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

}

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

<强>更新

这是未经测试但可能适用于将服务注入isAllowed

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

  

注入器提供了DynamicComponentLoader。

这可能是获取应用程序的主注入器使用的相同单例实例的黄金票。理论上这应该有效

在您的启动文件中

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

然后在带有isAllowed方法的文件中

import {applicationInjector} from '...';

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