How can I implement a loader animation in Angular while fetching data from an API?

Is there a better way to display a loader while fetching data from an API? Currently, I am showing the loader if the product list length is 0, but I feel this approach is not optimal. Any suggestions on how I can improve this?

HTML:

<div *ngIf="!CoffeeItemList?.length" class="mt-5 text-center">
     <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
</div>

TS:

constructor(private getDataListingService: DataListingService) {}

ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
    }
    });
  }
  getSmartSearchValues(search) {
    if (search === '' ) {
      this.getAllData();
      return false;
    } else {
      this.getGlobalSearchList(this.type);
      this.searchText = this.type;
      }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}

Answer №1

To begin, start by setting a default value of false for showLoader in your component.ts file.

getAllData() {
    this.showLoader = true;
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
      this.showLoader = false;
    });
  }
<div *ngIf="showLoader" class="mt-5 text-center">
       <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
    </div>

Finally, make sure to add the condition *ngIf="!showLoader" where you display the data.

Answer №2

Using ng if else and finalize pipe in the following manner:

  retrieveFilteredResults(filter) {
    if (filter === '' ) {
      this.getAllItems();
      return false;
    } else {
      this.getFilteredItemList(this.category);
      this.filterText = this.category;
      }
    this.loadingData = true;
    this.dataService.fetchFilteredList(filter).pipe(
    finalize(() => {
      this.loadingData = false;
    })
  ).subscribe(response => {
      this.filteredItemList = response.data;
    });

  }
<div *ngIf="!loadingData; else showLoading" class="mt-5 text-center">
       <img src="https://example.com/images/loader.gif"/>
    </div>
<ng-template #showLoading>
 Loading...
</ng-template>

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

Implementing secure HTTPS for an Angular 6 application

Currently, I have an Angular 6 application running on a Tomcat web server. The server-side of the app is implemented in Java using the Spring framework and deployed on another Tomcat web server. I am looking to implement secure SSL for my entire applicat ...

The Angular application shell build has produced two new folders within the dist directory. I'm curious about their purpose and how they can

Whenever I execute the ng run my-app:app-shell -c production command, it creates 2 folders within the dist directory - one for the browser and one for the server. Now, I find myself with 2 different commands to use: npm build --prod (for a regular build) ...

Can a unique custom command be designed for the Kendo UI Grid in Angular2?

The built-in commands supported by the KendoUI Grid for Angular2 include: kendoGridAddCommand kendoGridCancelCommand kendoGridEditCommand kendoGridRemoveCommand kendoGridSaveCommand However, I am working on a project that requires a custom command to be ...

How can I properly specify the type of a function for a complex object with index signatures in TypeScript?

Problem with Retrieving Specific Data from Mixed Object I'm encountering an issue with a function that is supposed to retrieve a specific piece of data within an object. The object contains a combination of known indexes and index signatures, which s ...

Filtering multiple columns in Angular Material's mat-table

I am attempting to integrate a filter into my table. You can view the table with the filter in action on this live demo. However, I am facing an issue where the filters are not narrowing down the results as expected. For instance, when I apply the ID filt ...

Is it possible to selectively exclude features such as routes and components from my Angular application during the build process based on the environment configuration file?

I am interested in creating two variations of my Application using the same codebase. One version will have the "registration" feature included, while the other will not. Is there a way to configure Angular so that an environment file dictates what is ex ...

White Background Dialog in Angular

I am struggling to change the default white background of my webpage. Is there a way I can use CSS to blur or darken the background instead? I tried applying CSS code but couldn't locate the correct class. I also attempted setting the "hasBackdrop" at ...

After I deploy my Next.js code to Vercel, including Google Analytics added by @next/third-parties, I am encountering an error that does not appear in development mode

Lately, I completed a next.js project and integrated Google Analytics using @next/third-parties/google. During development, everything worked perfectly, but upon deploying it to vercel.com, an error popped up. ` ./app/layout.tsx:3 ...

Installing express in typings: A beginner's guide

I'm currently incorporating expressjs into my application. Following its installation using typings install express --ambient --save, I run tsc. However, two errors are returned: typings/main/ambient/express/index.d.ts(17,34): error TS2307: Unable ...

What kind of parameter can be specified for a generic method that will not actually be called?

Currently, I am attempting to create a method that includes a parameter with a generic type. In this case, I have used 'unknown' as the generic type since it is not needed: function f(op: Operation<unknown>): void {...}. However, this appro ...

The NodeJS namespace appears to be missing

I'm currently utilizing Ionic2 in conjunction with socket.io Upon running ionic serve, I encounter the following error message in the terminal: TypeScript error: typings/globals/socket.io/index.d.ts(357,30): Error TS2503: Cannot find namespace &apos ...

Change a `as const` object into a type that is more broadly applicable

Creating a Generic Type from an Immutable Object Using "as const" Consider the following immutable object: const usersDefaultValues = { firstName: '', isGuest: false } as const We aim to generate the following type/interface based on this o ...

Utilizing headers in apollo watchQuery results in undefined data

Utilizing the apollo-angular package for querying our backend using graphQL has been smooth sailing. However, things take a turn when I attempt to include headers in the query. I am specifically adding a custom header to extract flattened data from the ba ...

Deactivation within the directive does not entail a reset

Check out this Stackblitz In my Angular application, I implemented a Directive that disables a button after it's clicked to prevent double-clicking until a certain time has passed. <button appThrottleClick (throttleClick)="click()"> BUTTON & ...

Error in Javascript: unable to locate the imported module

When attempting to import the 'CryptographyClient' module from a specified directory, I encountered an issue. Initially successful in typescript, but after compiling the code into javascript, an error was thrown stating that it could not find the ...

How can I implement email authentication in Angular using Firebase?

After only a month of playing around with Angular, I have managed to develop a web app with login and signup forms using Firebase for data storage and authentication. Typically, new users are required to sign up before logging in. However, I now face a di ...

Be cautious when mentioning unbound methods that could lead to unintended scoping of the `this` keyword

Hey there! Any suggestions on how to avoid encountering this error related to unintentional scoping issues with unbound methods? Code snippet: You are seeing multiple errors (like 16:41, 16:62, 17:34) indicating that referencing unbound methods without ne ...

In what way can you retrieve scope values (when testing) from an Angular controller implemented in TypeScript?

When working with Angular controllers in TypeScript, you have the option to define your controller in a way that accepts the $scope as an input parameter: class TestCtrl { constructor($scope:ng.IScopeService) { $scope.myData = "Information"; ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...