I have an Angular 2 app which I'd like to keep as lean as possible (traffic-wise) and load certain data sets (from API URL) only when it is required.
The service that is responsible for loading the data is passed to a ui component constructor as a dependency. The component template has many references to the service's properties and methods. I can initiate the data loading in the constructor, but since the loading happens asynchronously, the component is already rendered when the data arrives.
So, basically, I am looking for a way to defer the component rendering until the service is initialized with the fresh data loaded from API. Currently I have a basic route with component that checks if the service is initialized, and navigates to the final route when it has finished initialization. But this is not pretty because it requires two routes for one view.
You can do something like this;
Let's say that you are getting the data from your async call like this:
this.myService.myAsyncCall().subscribe((res)=>{...})
inside this async call lets say you are assigning the response to a field of the component
this.myService.myAsyncCall().subscribe((res)=>{
this.field = res.data.list;
})
and you don't want your template to get rendered until this data arrives so you can use an *ngIf inside your template:
<div *ngIf="field && field.length && field.length > 0">
...
</div>
This is just an approach. You can use the safe navigation operator(?) for smaller operations but since you haven't provided any info about your code, I have given a generic answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With