The loading template remains visible despite the Eventsource being closed when using the Async Pipe

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.

Answer №1

The reason why an empty array is considered a falsy value in JavaScript is because when evaluating truthiness, an empty array is considered as false. To account for this behavior, you can use the expression (ads$ | async).length >= 0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Margin is being overlapped by the DropDown

Encountering an issue with the DropDown component in Angular & Primeng. The DropDown utilizing "style=width:100%" is extending beyond the border when large text is selected. The width of the control should remain consistent regardless of text length. You ...

typescript Object that consists of properties from an array with a defined data type

I have an array consisting of strings. I am trying to transform this array into an object where each string is a property with specific attributes assigned to them. export interface SomeNumbers { name: string; value: number; } const arr = ['apple& ...

My goal is to create a carousel using Vue 3 with the Composition API and TypeScript

Creating a carousel with Vue 3 and TypeScript has been quite challenging for me. I heard about using "vue-awesome-swiper" to build a carousel, but I couldn't find a tutorial on how to use it. Does anyone know how to utilize this tool effectively? Alte ...

Retrieving the last segment of a URL in Angular

How do I extract the last segment of a URL? For instance, from /item/:id/edit, I want to isolate edit or /edit. I came across this question on Stack Overflow, but it doesn't seem to work for me as I need to execute this code in the parent component a ...

Choose historical dates with the dl-date-time-picker component within an Angular application

In my Angular 7 project, I have integrated a datetimepicker component called dl-date-time-picker. I want to prevent users from selecting previous dates in the date and time picker. Although I tried using the [selectFilter] attribute for this purpose, it en ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

What is the best time to initialize .env variables in a NodeJS application?

Building a NodeJS Express REST API with TypeScript requires loading environment variables using the dotenv package. In my code, I access the .env variables in two different files: index.ts, which serves as the entry point, and in a separate file called My ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

What is the reasoning behind referring to RxJS Subject as Multicast and Observable as Unicast?

I've been delving into RxJS for a while now and I'm struggling to grasp why we refer to RxJS Subject as Multicast and Observable as Unicast. I understand that Subject can emit data using next(), and like a regular Observable, we can subscribe to ...

Ngb-xx is not a recognized chemical property

Attempting to implement ngb bootstrap in my Angular project has been challenging. Errors keep popping up for every ngb component I try to use. https://i.sstatic.net/jF1xV.png Here's a glimpse of my package.json: https://i.sstatic.net/utqX6.png and ...

The additional parameters I am trying to append are being overwritten by the set parameters in the httpInterceptor

Issue Description: I have implemented an HttpInterceptor that adds an id and token to all requests when the user's credentials are available. However, I am facing the problem of the interceptor overwriting any additional HttpParams added to a request. ...

Encountering the issue of receiving an undefined value when attempting to define a {string} parameter within the "when" section of the step

As a novice in the world of protractor with cucumber, I am faced with the challenge of automating a process where inputting a first name, last name, and postcode creates a new user. In order to achieve this, I have attempted to define the data entry within ...

What is the process for activating shift key - multi-selection in the PrimeNG pick list?

I'm currently utilizing the prime ng pick list from the PrimeNG API located at: https://www.primefaces.org/primeng/#/picklist An issue I've encountered is that the picklist doesn't support multiple selections. For instance, in this example ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

What distinction can be drawn between binding to an attribute and binding to a property in Angular?

When we bind to data attributes, we typically use the syntax [attr.data-something]="expression". However, is it necessary to bind to properties like id, title, name in the same manner? Wouldn't binding to a property (without attr.) produce t ...

Steps for executing the `microsoftTeams.media.scanBarCode` API upon application launch

When my extension application in MS Teams invokes a URL, it opens an angular application. However, I'm encountering an issue where the microsoftTeams.media.scanBarCode API is not running when called within the OnInit method. Interestingly, the API r ...

Having trouble with Angular redirecting to the incorrect URL?

Currently delving into the world of Angular, I am eager to create a straightforward application where users can effortlessly switch between two components. The issue arises when attempting to navigate back from the navbar to the login component: <a rout ...