javascript - 如何修复加载不以 Angular 显示的问题

标签 javascript angular typescript

如何解决加载..不显示的问题。

这是代码: 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);
  });

}

我想做的是在获取数据的同时显示加载情况。

这里的问题是加载...不显示它自动显示无数据!

最佳答案

您的问题是 BehaviorSubject 是用 [] 初始化的,因此 *ngIf="tempThermometer | async 将始终为 true。您必须检查其长度是否为 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);
  });
}

关于javascript - 如何修复加载不以 Angular 显示的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60517843/

相关文章:

javascript - Node : Executing async functions on mocha startup

typescript - 如何在 typescript 中编写代码以在 tsc 之后在 javascript 中创建私有(private)成员?

javascript - 在 typescript 或 javascript 中链接箭头函数

angular - 等待异步函数返回 Typescript 中的值。

javascript - DOM 属性更改时触发事件

c# - 服务器和浏览器 ASP.NET MVC 之间的 CultureInfo 冲突

javascript - Ionic 4 Stripe.js 集成

angular - Angular 2 中模块导入的名称冲突 - 有没有办法防止它

node.js - 添加或更新在spurCommerce中不起作用的产品

javascript - 图像 slider CSS 和 jQuery