Within my Angular application, I am fetching data from two different APIs. The first API provides generic information about a set of items, while the second API returns corresponding images for those items.
To optimize the loading process, I have implemented a method where both API calls are made simultaneously. Once the generic data is retrieved (which should be faster), I display it to the user. Subsequently, I replace the generic data objects with the images obtained from the second API.
Currently, I am using forkJoin to combine the results of both API calls. However, this means that the items will only be displayed once both APIs have completed their tasks.
Below is a snippet of my code:
ngOnInit(): void {
forkJoin([this.negoziService.negozi(), this.negoziService.images()]).subscribe(data => {
this.arrNegozi = data[0];
data[1].map((i) => {
const image = this.arrNegozi.find((d) => d.id === i.id);
image !== undefined
? image.logo = 'data:image/jpg;base64,' + i.img
: image.logo = null;
});
}, error => {
this.errore = error;
})
}
EDIT:
I recently updated my code to use combineLatest
as recommended in some comments, but the behavior remains unchanged.
combineLatest([this.negoziService.negozi(), this.negoziService.images()]).subscribe(([nagozi, images]) => {
this.arrNegozi = nagozi;
images.map((img) => {
const negozio = this.arrNegozi.find((d) => d.id === img.id);
negozio !== undefined ? negozio.logo = 'data:image/jpg;base64,' + img.img : negozio.logo = 'assets/images/no_image.svg';
})
},
error => {
this.errore = error;
}
)
The intent behind this approach is to initially show a skeleton layout while the images are still loading. Once the text data from the first API is available, it should be displayed promptly.