When does ngOnInit run? Serious question

I don’t mean this to sound dismissive or disrespectful, but IMHO you don’t actually want to know this.

The reason I say that is that today’s answer might not be tomorrow’s answer, and once I “know” how things work today, I tend to (sometimes subconsciously, even) rely on the implementation details, which is a recipe for confusing bugs of the “damn, this always used to work” variety.

ngOnInit and ngOnDestroy are paired. You can rely on the fact that (if you implement both), neither will be called twice in a row without an intervening call to the other. That’s pretty much it.

You’re probably tired of seeing me flog this post, but I think you will be happier in the long run if you manage your data flow independently of Angular lifecycle events. Lifecycle events are about view-layer concerns, and IMHO it’s therefore awkward to try to force them into playing roles in model-layer-land.

All of that being said, if you’re still reading, yes, you’re basically right, and it’s not totally predictable.

The OS can reap your application at its sole discretion, if it decides it can better use the resources your app is consuming. You can subscribe to Platform pause and resume events to catch this. I sometimes do this, in order to “re-launch” things that are done only at launch time when the app is resumed. There is no explicit time limit - it’s all at the whim of the OS process scheduling.

pause will also vaporize and re-instantiate services.

1 Like