代码之家  ›  专栏  ›  技术社区  ›  Qusay Saad

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

  •  3
  • Qusay Saad  · 技术社区  · 7 年前

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

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

    <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() }));
    });
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Tsortanidis Christos    7 年前

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

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

    当然,如果您可以将计数器保留在数据库中的某个位置,这样您就不必只为一个数字而首先获取整个列表,这总是更好的,但这可能会非常有效,除非您的待办事项列表非常大。如果是的话,第一次出现这个数字要花很多时间。我希望这有帮助。