如何查找已完成项目的总长度?

How to find length of total completed items?

如何查找已完成项目的总长度?

如何查找已完成的项目总数(待办事项)?在项目列表中 如何在数组

中找到某个对象的长度
<div>Todo List:</div> {{(items | async)?.length}}  <-- Total Items in list

<div>{{(items.completed | async)?.length}}</div> <!-- Total completed items? - length of total completed items

<hr>

<ul *ngIf="todo_all">
    <li *ngFor="let item of items | async"  [class.completed]="item.completed">
        {{item.description}}
    </li>
</ul>


itemsRef: AngularFireList;
items: Observable<Todo[]>;

constructor(db: AngularFireDatabase) {
this.itemsRef = db.list('todos')
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
}

实际上,您可以从现有的可观察对象中过滤您在客户端上拥有的项目,或者进行简单的查询以仅获取已完成的项目。

completedItemsCount: Observable<number>;

一种方式:

this.completedItemsCount = items
.map(items => 
    items.filter(item => item.completed).length
); // Maps the observable, filters the completed and return its length

另一种方式:

this.completedItemsCount = db
.list('/todos', ref => ref.orderByChild('completed').equalTo(true))
.map(changes => {
    return changes.map(c => (
        { 
            key: c.payload.key,
            ...c.payload.val(),
        }
    )).length; // Eventually return the length
});

当然,如果您可以将计数器保存在数据库中的某处,那总是更好,这样您就不必为了一个数字而首先获取整个列表,但这仍然可能会很好用,除非您的待办事项列表是真的非常巨大。如果是,第一次出现该数字将花费大量时间。希望对您有所帮助。