angular - 来自 RouterStateSnapshot 的角度检查组件实例
问题描述
我正在尝试实施canDeactivate
警卫。为此,我需要知道要导航到的路由的组件实例。
canDeactivate(
component: ComponentCanDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean> {
return new Observable((observer: Observer<boolean>) => {
console.log('componet', component);
console.log('state', state);
console.log('nextstate', nextState);
this.routerService.doSomething(nextState, route);
observer.next(true);
});
}
我想知道是否可以从 nextState 获取组件?我试过这样的事情:
nextState.root.component
但它返回AppComponent
给我,因为这不是我要导航到的组件的名称。
我该怎么做呢?或者我应该以其他方式获得一个实例?
编辑:
我可以在 RouterStateSnapshot 内的浏览器的开发人员终端中看到组件实例(NextComponent)->
_root: TreeNode
url: "/Nextcomponent/15708/childcomponent"
_root: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: Array(1)
0: TreeNode
children: []
value: ActivatedRouteSnapshot
component: class NextComponent
^^^^^^^^^^^^^
但无法在我的代码中获取它。
解决方案
I see 2 things:
- you should never use
new Observable()
, and and I don't see why you put your code inside an observable (you may just remove the Observable). - I would recommand implementing a method
canDeactivateMyFeatureGuard
in your component. You can make your component implement a genericAppCanDeactivateMyFeatureGuard
(where your guard is namedMyFeatureGuard
), which definescanDeactivateMyFeatureGuard
.
Then you call this method in the guard.
It would look like this:
export class MyComponent implements AppCanDeactivateMyFeatureGuard {
// ...
canDeactivateMyFeatureGuard(): boolean {
return this.isLocked; // or whatever condition owned by the component, or service call...
}
}
and the guard:
export class MyFeatureGuard implements CanDeactivate {
// ...
canDeactivate(
component: ComponentCanDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
nextState: RouterStateSnapshot
): boolean {
// logic is now in each component, where it can handle the way you wish.
return component.canDeactivateMyFeatureGuard();
}
}
推荐阅读
- c++ - 初始化指针和矩阵数组
- kubernetes - 将 sidecar 容器日志拖尾到现有 pod
- spring-security - 无法解密 EncryptedData (SAML2)
- google-apps-script - 如何在谷歌脚本中循环谷歌表格粘贴转置公式
- python - Websockets客户端不打印消息——Python
- unity3d - Unity2D - 区域颜色反转
- django - 是否有内置方法可以为 ManyToManyField 设置最大关系大小?
- javascript - node.is 中的电子邮件验证编码
- visual-studio - 条件测试柏树
- c - 我的程序只在特定情况下才有效