如何检查Firestore集合是否为空?

时间:2018-03-01 05:50:13

标签: angular firebase angular-material google-cloud-firestore

我正在使用Angular和Angularfire2。

我想检查Firestore集合是否为空。我正在制作一个待办事项应用,我想在Material guidelines中显示一个空状态容器。

这是我的数据结构:

users/
  userID/
    todos/
      // etc.

我使用以下代码:

<div class="empty-state-container" *ngIf="isTodosEmpty">
    <div class="empty-state-div">
        <h2>All todos have been done!</h2>
        <p>Go reward yourself with exercising, reading or your favourite hobby.</p>
        <button mat-raised-button (click)="newTodo()" color="primary">Create a new todo</button>
    </div>
</div>

<!-- ... -->

我的组件:

export class MyComponent {
    isTodosEmpty: boolean;

    constructor(
        private fs: AngularFirestore,
        private afAuth: AngularFireAuth,
        // ...
    ) {
        afAuth.auth.onAuthStateChanged((user) => {
        if (user) {
            console.log(user);
            this.currentUser = user.uid;
            this.todosCollection = this.fs.collection(`users/${this.currentUser}/todos`);
            this.todos$ = this.todosCollection.snapshotChanges().map(actions => {
                return actions.map(a => {
                    const data = a.payload.doc.data() as TodoItem;
                    const id = a.payload.doc.id;
                    return { id, ...data };
                });
            });
        } else {
            console.warn('Current user doesn\'t exist yet!');
        }
    });
    }
}

3 个答案:

答案 0 :(得分:4)

您可以在模板

中实现此目的
<ng-container *ngIf="todos$ | async; let todos; else nocontent">
    <div *ngFor="let todo of todos">
        {{todo | json}}
    </div>
</ng-container>
<ng-template #nocontent>
    <div class="empty-state-container">
        <div class="empty-state-div">
            <h2>All todos have been done!</h2>
            <p>Go reward yourself with exercising, reading or your favourite hobby.</p>
            <button mat-raised-button (click)="newTodo()" color="primary">Create a new todo</button>
        </div>
    </div>
</ng-template>

<ng-template #nocontent>此部分将显示todos$是否为空。

答案 1 :(得分:2)

我设法通过关注@ Hareesh的答案解决了问题,但我检查了todos$ ObservableArray)的长度是否大于0,如果不是,它仍然会显示空状态容器:

<ng-template #emptystate>
    <div class="empty-state-container">
        <div class="empty-state-div">
            <h2>All todos have been done!</h2>
            <p>Go reward yourself with exercising, reading or your favourite hobby.</p>
            <button mat-raised-button (click)="newTodo()" color="primary">Create a new todo</button>
        </div>
    </div>
</ng-template>
<ng-container *ngIf="(todos$ | async)?.length > 0; else: emptystate">
    <!-- ... -->
</ng-container>

编辑:我的工作效果不好,因为即使Firestore集合中没有内容,也不会显示空状态。因此,Hareesh的回答是正确的。

答案 2 :(得分:0)

一个简单的答案:

<div *ngIf="( todos$ | async)?.length > 0">Populated</div>
<div *ngIf="( todos$ | async)?.length == 0">Empty</div>

您只想远离!( (todos$ | async)?.length > 0 ),因为这样一来,它始终会在第二(空)状态下启动,然后在第二秒钟弹出时自动将其切换到填充状态。