Panda
Panda

Reputation: 415

How to fix the loading doesn't display in angular

How to fix the issue where the loading.. doesn't display.

here's the code: HTML

     <div *ngIf="tempThermometer | async as temp; else loading">
        <ng-container *ngIf="temp.length !== 0; else noItems">
          <div *ngFor="let item of temp">
            {{temp.sensor}}</div>
        </ng-container>
        <ng-template #noItems>No Items!</ng-template>
      </div>
      <ng-template #loading>loading animation...</ng-template>

TYPESCRIPT

 tempThermometer = new BehaviorSubject<any>([]);
async getRoomList() {
    this.subscription = await this.global
      .getData(`/conditions/latest`)
      .pipe(take(1))
      .subscribe((res: any) => {
        this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
          return {
            ...obj,
            spinning: true
          };
        })));

        console.log(this.tempThermometer.value);
  });

}

what I want to do is to display the loading while fetching the data.

the issue here is the loading... doesn't display it automatically display the No Data!

Upvotes: 0

Views: 668

Answers (1)

AliF50
AliF50

Reputation: 18859

Your issue is that the BehaviorSubject is initialized with [] and therefore *ngIf="tempThermometer | async will always be true. You have to check for its length being 0 but I see you do a check for its length being 0 and display No Items!

Try:

<ng-container *ngIf="!tempLoading">
 <div *ngIf="tempThermometer | async as temp">
    <ng-container *ngIf="temp.length !== 0; else noItems">
       <div *ngFor="let item of temp">
         {{temp.sensor}}
       </div>
     </ng-container>
     <ng-template #noItems>No Items!</ng-template>
  </div>
</ng-container>
<div *ngIf="tempLoading">loading animation...</div>
tempLoading = false; // new variable to show loading or not, can initialize it to true depending on your use case
tempThermometer = new BehaviorSubject<any>([]);
getRoomList() { // remove async, nothing async about this function
    this.tempLoading = true;
    this.subscription = this.global
      .getData(`/conditions/latest`)
      .pipe(take(1))
      .subscribe((res: any) => {
        this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
          return {
            ...obj,
            spinning: true
          };
        })));
        this.tempLoading = false; // set the loading to false
        console.log(this.tempThermometer.value);
  });
}

Upvotes: 1

Related Questions