Angular 2.1.0,路由器3.1.0。
在创建仪表板组件时,我注意到每次我路由到它时 - 它都是从头开始创建的。然后我检查了英雄之旅演示插件 - 相同的行为。
DashboardComponent
的修改
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) {
console.log('DashboardComponent constructor')
}
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
console.log('DashboardComponent ngOnInit')
}
}
这是plunker 。打开开发者控制台。运行 plunker - 应该看到 2 个日志:DashboardComponent constructor
和DashboardComponent ngOnInit
。点击Heroes
返回Dashboard
- 再次记录 2 条日志:构建和调用 ngOnInit
.
Plunker 可能会使用旧的库。我从 John Papa git 克隆了 TOH (在撰写本文时,他使用相同版本的 Angular 和路由器)并更改了 DashboardComponent
拥有这些控制台日志。结果 - 相同。
我已添加ngOnDestroy
至DashboardComponent
在离开仪表板时调用它。所以它看起来像是设计行为。什么是好处?如何重用已创建的组件?
最佳答案
>= 2.3.0-rc.0
可以实现自定义的RouteReuseStrategy
来控制路由组件何时被销毁、重新创建或重用。
- https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html
- https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx
- https://github.com/angular/angular/issues/7757
原创
这是“按设计”。当导航离开路线时,该组件会被销毁;当导航回路线时,该组件会被重新创建。
仅当路由参数发生变化但路由保持不变时,组件才会被保留。
有人讨论过一些自定义缓存策略,但据我所知,在这个方向上还没有采取任何行动。
关于Angular 2.1 - 在路由时重新创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466702/