如何通过ActivatedRouteSnapshot访问组件?



用例

使用Angular Guard的CanActivate来保护组件。

样本路径

{
path: "my-path",
component: MyComponent,
canActivate: [AuthGuard]
}

MyComponent作为样例组件

export class MyComponent {
// Dependency required by AuthGuard to allow/deny access
// Each component declares resources that it guards, along with access levels
static guardedResources = [
{"user_profile" : {"access" : "write"}},
{"posts" : {"access" : "read"}}
];
}
<<p>AuthGuard代码/strong>
canActivate(route: ActivatedRouteSnapshot) {
// Component resolution happens at runtime via route.component

// Common logic to read component's guardedResources and match them against
// user's access privileges lies here
}

当我试图通过route.component.guardedResources访问组件属性时,它抛出

error TS2339: Property 'guardedResources' does not exist on type 'string | Type<any>'.
Property 'guardedResources' does not exist on type 'string'.

console.log(route.component)显示我的组件的身体在控制台上,所以我相当有信心,我可以解决这个问题通过类型转换route.component适当地通过guardedResources

可能的解决方案

步骤1 -在基类中抽象guardedResources,并在派生组件中重写该属性。

步骤2 -将route.component类型转换为这个基类,以便guardedResources作为一个有效的属性可用。

我想我在这里缺少了一些Angular或TypeScript的基本知识。有人能告诉我相关的链接/文档,我可以参考?

route.componentcomponent的类型保存为stringType<any>,因此如果您想从中获得静态guardedResources,则必须在此之前将其强制转换为MyComponent类型,如下所示:

// To make sure that the component type is `MyComponent`
if (route.component === MyComponent) {
// Cast the type of route.component` to the type of `MyComponent` to access its static variables:
const guardedResources = (route.component as typeof MyComponent).guardedResources;
// Do the other stuff here
}

在这个链接上有一个类似的答案。处理这个问题的另一种方法,可能是用一个常量处理paths与你试图匹配的内部对象:

export const ROLES = {
'my-path': {
{'user_profile' : {'access' : 'write'}},
{'posts': {'access' : 'read'}}
}
}

然后在您的保护下,您可以简单地检查route的路径并执行必要的逻辑,而不需要强制转换组件。

我想那样可能更干净。

最新更新