How can I resolve the issue I'm facing with the Angular async pipe and event source while using Spring boot WebFlux? I need to display a "loading data" message until the API call is complete. Once the API fetches data, I want to show the retrieved data. If the API response is empty, I want to display a "no data found" message.
My code functions correctly when data is available. However, if the API does not return any data, the "loading data" message still persists on the template. Here is the snippet of my code.
In my service.ts file, I am using an event source.
loadData():Observable<Advertisement[]>{
return new Observable((observer: Observer<any>) => {
const eventSource = new EventSource(
'My API Call'
);
eventSource.onmessage = (event) => {
this.zone.run(() => {
const json = JSON.parse(event.data);
this.adList.push(json);
observer.next(this.adList);
});
};
eventSource.onerror = (error) => {
observer.complete();
eventSource.close();
};
return () => eventSource.close();
});
}
In my component.ts file
this.ads$ = this.businessService.loadData(); //inside ngOnInit
My Template HTML structure is as follows.
<div *ngIf="ads$ | async as adsList; else loading">
<div *ngFor="let ad of adsList">
{{ad.name}}
</div>
<div *ngIf="adsList.length===0">
No Data Found
</div>
</div>
<ng-template #loading>
<div>Loading Advertisements .:.</div>
</ng-template>
Can anyone assist me in resolving this issue? I have successfully implemented the same logic for non-array objects from the event source, but it does not work for arrays.