找到与AngularFire2列表匹配的值

时间:2017-02-21 21:36:45

标签: angularfire2

如果我有以下火力列表

Class
   0
    name:'class 1'
    type:'A'
   1
    name:'class 1'
    type:'B'
   2
    name:'class 1'
    type:'A'

如何将所有类型'A'更新为'C'?

1 个答案:

答案 0 :(得分:2)

您需要先执行查询然后再进行更新 - multi-location update最好:

import "rxjs/add/operator/first";
import "rxjs/add/operator/toPromise";

angularFire.database

  // Query all of the elements that have type equal to A:

  .list("Class", {
    query: {
      orderByChild: "type",
      equalTo: "A"
    }
  })

  // Use the first operator to complete the observable, as
  // only the first emitted list is required:

  .first()

  // The update call will return a promise that resolves to
  // void, so the observable might as well be converted to a
  // promise:

  .toPromise()

  // Build a multi-location update so that all of the matching
  // elements can be updated simultaneously:

  .then(list => {

    if (list.length > 0) {
      let multi = {};
      list.forEach(element => {
        multi[`${element.$key}/type] = "C";
      });
      return angularFire.database
        .object("Class")
        .update(multi);
    } else {
      return Promise.resolve();
    }
  });