Как исправить загрузку не отображается в angular - PullRequest
0 голосов
/ 04 марта 2020

Как решить проблему, когда загрузка .. не отображается.

вот код: 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);
  });

}

я хочу отобразить загрузку при получении данных.

проблема здесь заключается в загрузке ... не отображается автоматически отображение данных нет!

1 Ответ

1 голос
/ 04 марта 2020

Ваша проблема в том, что BehaviorSubject инициализируется с [] и, следовательно, *ngIf="tempThermometer | async всегда будет истинным. Вы должны проверить его длину, равную 0, но я вижу, что вы делаете проверку его длины, равной 0, и выведите на экран No Items!

Попробуйте:

<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);
  });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...