Angular2 - ngOnDestroy() 未在类似路线上调用 [英] Angular2 - ngOnDestroy() not called on similar route
问题描述
我有一个 Angular2 应用程序,其路径如下:
I have an Angular2 app with a route like this:
{
path: '',
component: ContentComponent,
children: [
{
path: 'folder/:folderId',
resolve: {
currentFolder: CurrentFolderResolver,
},
children: [
{
path: '',
resolve: {
folderStructure: FolderStructureResolve,
},
component: FolderOverviewComponent,
},
{
path: 'users',
component: UsersComponent,
}
]
}
]
}
当从像 /folder/123 这样的路由导航到 /folder/456 时,Angular 不会在 ngOnDestroy()
中触发 ngOnDestroy()
代码>FolderOverviewComponent.导航到 /folder/456/users 就可以了.
When navigating from a route like /folder/123 to /folder/456, Angular will not trigger ngOnDestroy()
in the FolderOverviewComponent
. Navigating to /folder/456/users will do.
换句话说,如果路由没有改变(忽略 :folderId 的动态部分),Angular 似乎不会销毁组件.这看起来很合理,但我需要清理 ngOnDestroy()
中的东西.
In other words, it seems like Angular does not destroy the component if the route does not change (ignoring the dynamic part of :folderId). This seems reasonable, nevertheless I need to clean up things in ngOnDestroy()
.
我可以将路由配置为每次导航到新路由时调用 destroy 吗(即使用不同的参数)?
Can I configure Routes to call destroy each time I navigate to a new route (i.e. with a different parameter)?
推荐答案
这是设计使然.如果只有一个路由参数改变导致使用相同的路由,则组件不会被销毁和重新创建,而是被重用.
That's by design. If only a route parameter changes which leads to the same route being used, the component is not destroyed and recreated but reused.
您可以订阅 params
更改,以便能够在路由更改时执行代码:
You can subscribe to params
changes to be able to execute code when the route was changed:
constructor(router: ActivatedRoute) {
router.params.subscribe(param => routeChanged(param['folderId']));
}
有计划在未来提供更多的灵活性,但目前就是这样.
There are plans to provide more flexibility in the future, but currently that's the way to go.
另见https://angular.io/guide/router#activated-route-in-action
这篇关于Angular2 - ngOnDestroy() 未在类似路线上调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!