Angular 4 - Can OnDestroy be run without the OnInit ever being triggered?

后端 未结 1 1054
醉酒成梦
醉酒成梦 2020-12-11 09:44

Just a generic question regarding the two Lifecycle Hooks OnInit and OnDestroy. As this article mentions, I had always assumed that OnInit

相关标签:
1条回答
  • 2020-12-11 10:03

    The reference clearly states that OnInit lifecycle hook precedes OnDestroy. This behaviour is specific to the compiler in general. The article explains the behaviour that is specific to Angular router and the way <router-outlet> directive instantiates components. router.navigateByUrl() in route component constructor triggers its immediate destruction and prevents it from being compiled, so the lifecycle isn't applicable to it. This won't happen under normal circumstances.

    The code in the question doesn't imply that ngOnInit doesn't run. ngOnInit call be easily logged to prove that it runs.

    The service that is used by this component can cause the problem. The fact that Cannot read property 'fade' of undefined or similar error is thrown in ngOnDestroy means that this.soundService.getSound(Sound.MINI_GAME_BG_MUSIC) is undefined.

    This totally depends on what happens inside soundService service. If loadSound is asynchronous, and ngOnDestroy was called before a resource was loaded, there may be problems.

    0 讨论(0)
提交回复
热议问题