Angular 如何在从 API 获取数据时添加加载器动画?

3 typescript angular

我试图显示加载程序从 API 获取数据时,我应该如何实现这一点,请帮助。截至目前,如果产品列表的长度为 0,那么我将向加载程序显示这不是正确的方法

HTML:

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

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

  }
}
Run Code Online (Sandbox Code Playgroud)

Vij*_*ati 5

首先,声明 in component.ts-showLoader默认 false。

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

最后在显示数据的地方*ngIf="!showLoader"添加此条件。