arrays - 如何检查可观察数组的大小?
问题描述
我正在使用 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”>
ITEMS:
<div *ngFor="let 1DArray of 2DArray$ | async">
<div *ngFor="let item of 1DArray">{{ item.id }}</div>
</div>
</div>
<div *ngIf=“!itemsExist”>
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 吗?
有什么方法可以检查可观察数组的长度?
解决方案
| async
您可以使用管道实现此目的。
例子:
<div *ngIf="(2DArray$ | async)?.length !== 0">...</div>
推荐阅读
- python - Zimbra zmrov 格式化文件到 csv 和 ldif
- c# - 如何在 Asp.Net Core 2.1 中使用 Identity Server 3 验证承载访问令牌
- intellij-idea - Intellij Idea - 如何在保存所有操作时更新应用程序
- authentication - “jti”、“client_secret”和“exp”如何用于验证“id_token”?
- javascript - 使用两个不同的.map() 两次映射异步函数?
- javascript - PHP,JS:鼠标悬停预览不起作用,默认情况下始终显示图像
- ag-grid - AG-Grid - 如何获取父 headerName
- php - 将用户名从 SP 发起的登录发送到预填写 IdP 登录表单?
- node.js - Node.js 中基于线程的函数?
- php - PHP表单验证在提交时不起作用?