Angular components gets duplicated on route change

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

当我在 Angular 项目中更改路线时,例如从

home
settings
再回到
home
,然后所有变量都会从页面
home
复制并且永远不会被破坏。

我在

home
组件中创建了一个循环来打印时间戳,每次我执行上面的测试用例时,计时器都会打印越来越多的信息。

我怎样才能防止这种行为?

接口路由.module.ts

const routes: Routes = [
  {
    path: '',
    component: InterfaceComponent,
    children: [
      {
        path: 'home', component: HomeComponent
      },
      {
        path: 'settings', component: SettingsComponent
      },
      {
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  }
];
angular typescript ionic-framework router
1个回答
0
投票

Angular 文档 说:

ngOnDestroy():在 Angular 销毁指令或组件之前进行清理。取消订阅 Observables 并分离事件处理程序以避免内存泄漏。请参阅本文档中实例销毁清理中的详细信息。

因此,您应该像这样“取消”

ngOnDestroy
生命周期挂钩中的所有类变量:

ngOnDestroy() {
    this.yourVariable = null;
}
© www.soinside.com 2019 - 2024. All rights reserved.