async/await in Angular `ngOnInit`

It is no different than what you had before. ngOnInit will return a Promise and the caller will ignore that promise. This means that the caller will not wait for everything in your method to finish before it proceeds. In this specific case it means the view will finish being configured and the view may be launched before this.data is set.

That is the same situation you had before. The caller would not wait for your subscriptions to finish and would possibly launch the app before this.data had been populated. If your view is relying on data then you likely have some kind of ngIf setup to prevent you from accessing it.

I personally don’t see it as awkward or a bad practice as long as you’re aware of the implications. However, the ngIf can be tedious (they would be needed in either way). I have personally moved to using route resolvers where it makes sense so I can avoid this situation. The data is loaded before the route finishes navigating and I can know the data is available before the view is ever loaded.

Leave a Comment