Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular How to add a loader animation while Fetch data from API?

I tried to show loader While fetching data from API, how should I achieve this, please help. as of now if the length of product list is 0 then I'm showing loader bt this is not the proper way

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;
    });

  }
}

1 Answers

First, declare in component.ts - showLoader default false.

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>

Last where you show data *ngIf="!showLoader" add this condition.

like image 146
Vijay Prajapati Avatar answered Aug 15 '26 09:08

Vijay Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!