Angular2 - ngOnDestroy()未在类似路线上调用

问题描述 投票:6回答:1

我有一个Angular2应用程序,其路径如下:

{
  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()中触发FolderOverviewComponent。导航到/ folder / 456 /用户可以。

换句话说,如果路径没有改变,似乎Angular不会破坏组件(忽略:folderId的动态部分)。这似乎是合理的,但我需要清理ngOnDestroy()中的东西。

每次导航到新路线(即使用不同的参数)时,是否可以将路由配置为调用destroy?

angular angular2-routing
1个回答
5
投票

这是设计的。如果只有路径参数发生变化而导致使用相同的路径,则不会销毁和重新创建组件,但会重复使用。

您可以订阅params更改,以便在路由更改时执行代码:

constructor(router: ActivatedRoute) {
  router.params.subscribe(param => routeChanged(param['folderId']));
}

有计划在未来提供更多的灵活性,但目前这是可行的方法。

另见https://angular.io/guide/router#activated-route-in-action

© www.soinside.com 2019 - 2024. All rights reserved.