Angular2 - ngOnDestroy() not called on similar route

只谈情不闲聊 提交于 2019-12-18 04:15:11

问题


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,
        }
      ]
    }
  ]
}

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.

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().

Can I configure Routes to call destroy each time I navigate to a new route (i.e. with a different parameter)?


回答1:


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.

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.

See also https://angular.io/guide/router#activated-route-in-action



来源:https://stackoverflow.com/questions/40678321/angular2-ngondestroy-not-called-on-similar-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!