【问题标题】:How to find length of total completed items?如何查找已完成项目的总长度?
【发布时间】:2018-01-10 09:55:21
【问题描述】:

如何计算已完成项目的总长度?

如何查找已完成的总项目(待办事项)?在项目列表中 如何在数组中找到某个对象的长度

<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() }));
});
}

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2 angular5


    【解决方案1】:

    实际上,您可以从现有的 observable 中过滤客户端上的项目,也可以进行简单的查询以获取已完成的项目。

    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
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多