Im working in Angular 14, and Im loading a page with content. Some of the content though, is retrieved from an outbound service call, and I have a loading screen while the content is loading.
I have an *ngIf statement on my loading spinner, and I set that variable to true while I make my call. When the content comes back, I set the variable to false, which should now display the full content.
The behavior Im seeing is that the screen loads, and spinner disappears and then a few seconds later my content pops up.
Im looking into some of these Angular lifecycle hooks, and Im wondering if there's a way to use these to set that variable to false once all my ngOnInit() operations are fully completed.
Thanks in advance.
There isn't an inbuilt way of doing this, mainly because your
ngOnInit()could contain an async function and Angular can't guarantee when that function has finished (without forcing the developer into some pattern where they have to return a Promise/Observable from withinngOnInit()etc).However, you can build an equivalent yourself (not in
ngOnInit, but within the functions you are using). This is actually more flexible than being tied to an Angular lifecycle hook as you can set your loading state wherever (and whenever) you want to deploy your functions.In most applications, you will have some source of data arriving asynchronously, so typically you would use RxJS to combine all of your asynchronous sources and update your loading state when all data sources have either returned successfully or errored.
For example:
synchronous exampleasynchronous example