首页 > 解决方案 > 如何检查可观察数组的大小?

问题描述

我正在使用 Angular 6 应用程序,我需要一种方法来判断我的 2D 可观察数组是否为空。

这是我的模板:

<div *ngFor="let 1DArray of 2DArray$ | async">
  <div *ngFor="let item of 1DArray">{{ item.id }}</div>
</div>

这给了我一个ID列表。

这是我的组件代码:

  this.allItems$ = [];
  source.forEach(obj => {
    const colRef$ = this._firestoreService.colWithIds$(`Collection/${obj.id}/SubCollection`); // a collection of items
    this.allItems$.push(colRef$); // an array of collections (2D array)
  });
  this.2DArray$ = Observable.combineLatest(this.allItems$); // an observable of the 2D array

这给了我一个二维数组的可观察值。

我的问题是,如果没有要从 firebase 集合中检索的项目,则 2D 数组不会为空。相反,它将由一堆空的一维数组组成:

[
[],
[],
…
]

我想在页面上的项目列表上方放置一个标签,例如“ITEMS:”。但是如果没有项目,我想取消这个标签。

我可以通过设置一个标志来做到这一点,比如 itemsExist: boolean。我会这样设置:

this.itemsExist = false; 
this.allItems$ = [];
source.forEach(obj => {
    const colRef$ = this._firestoreService.colWithIds$(`Collection/${obj.id}/SubCollection`); // a collection of items
if (colRef$.length > 0) {
        this.allItems$.push(colRef$); // an array of collections (2D Array)
    this.itemsExist = true; 
}
  });
  this.2DArray$ = Observable.combineLatest(this.allItems$); // an observable of the 2D array

…然后用 *ngIf 将列表包装在模板中:

<div *ngIf=“itemsExist”&gt;
ITEMS:
  <div *ngFor="let 1DArray of 2DArray$ | async">
    <div *ngFor="let item of 1DArray">{{ item.id }}</div>
  </div>
</div>
<div *ngIf=“!itemsExist”&gt;
  There are no items to display.
</div>

但我不能在 observable 上使用 .length 。我无法检查数组 observable 上存在多少项。当然,除非您订阅它。然后你就得到数组,你可以检查它的长度。我尝试过这样的事情:

  this.allItems$ = [];
  source.forEach(obj => {
    const colRef$ = this._firestoreService.colWithIds$(`Collection/${obj.id}/SubCollection`); // a collection of items
    this.allItems$.push(colRef$); // an array of collections (2D array)
  });
  this.2DArray$ = Observable.combineLatest(this.allItems$); // an observable of the 2D array
this.itemCount = 0;
this.2DArray$.subscribe(item2DArray => {
    item2DArray.forEach(item1DArray => {
        this.itemCount += item1DArray.length;
    });
});

然后我在 *ngIf 中检查 itemCount。

但是即使其中有项目,我的列表也根本不会显示。我还尝试订阅 colRef$ 并检查 1DArray 的长度,仅当它大于 0 时才将其添加到 allItems$,但效果相同。订阅后可以在 *ngFor 循环中使用 observable 吗?

有什么方法可以检查可观察数组的长度?

标签: arraysangularobservablengfor

解决方案


| async您可以使用管道实现此目的。

例子:

<div *ngIf="(2DArray$ | async)?.length !== 0">...</div>

推荐阅读