首页 > 解决方案 > 角度异步数据

问题描述

我正在尝试从我的 api 获取数据,获取数据的代码:

getList() {
    this.fileList = [];

    this._globalService.getUserFiles(this.userId)
      .then(files => {
        files.forEach(retFile => {
          this._globalService.getFileActions(retFile._id)
            .then(retActions => {
              this.fileList.push( {
                file: retFile,
                action: retActions
              });
            });
        });
      })
      .finally(() => {
        this.finish = true;
      });
  }

调用 OnInit 钩子。之后,我的观点试图表明:

<ng-container *ngIf="finish; else wait">
      <ng-container *ngIf="fileList.length; else noItems">
        <li *ngFor="let item of fileList">
         ...
        </li>
      <ng-container>
      <ng-template #noItems>
        <span class="noItems">Any file</span>
      </ng-template>
<ng-container>

这很好用。但是我的问题持续了几秒钟,#noItems 模板将显示数据何时存在,就像在这个例子中一样:

在此处输入图像描述

标签: javascriptangularasynchronous

解决方案


您总是将结果推送到 this.FileList 中,您的 this.FileList 永远不会为空,因此您的 noItem 模板永远不会出现。


推荐阅读