如何一步删除列表查询结果?

时间:2016-11-11 16:06:07

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

我已尝试删除产品ID等于operations的{​​{1}}。 它删除了整个操作分支,而不仅仅是与查询结果相同的分支。

myProdID

我应该使用什么来在一行代码中执行它而不是运行for循环来删除每个项目? .map?

2 个答案:

答案 0 :(得分:2)

它只是一行代码,但你可以这样做:

deleteOperations(productID: any): Observable<any> {

  return this.af.database.list('operations', {
    query: {
      orderByChild: 'products/productID',
      equalTo: productID
    }
  })

  // AngularFire2 list/object observables don't complete - they re-emit if
  // the database changes - so use the first operator to ensure it completes
  // and ignores subsequent database changes.

  .first()

  // Use Array.prototype.reduce to create an object containing the keys to
  // be removed and use the FirebaseObjectObservable's update method to
  // remove them.

  .mergeMap((ops) => this.af.database.object('operations').update(
    ops.reduce((acc, op) => { acc[op.$key] = null; return acc; }, {})
  ));
}

上述函数将返回一个observable,并且在调用者订阅它时将执行删除。

如果您希望函数返回一个承诺,您可以执行以下操作:

deleteOperations(productID: any): Promise<any> {

  return this.af.database.list('operations', {
    query: {
      orderByChild: 'products/productID',
      equalTo: productID
    }
  })

  // AngularFire2 list/object observables don't complete - they re-emit if
  // the database changes - so use the first operator to ensure it completes
  // and ignores subsequent database changes.

  .first()

  // Convert the observable to a promise when that will resolve when the
  // observable completes.

  .toPromise()

  // Use Array.prototype.reduce to create an object containing the keys to
  // be removed and use the FirebaseObjectObservable's update method to
  // remove them.

  .then((ops) => this.af.database.object('operations').update(
    ops.reduce((acc, op) => { acc[op.$key] = null; return acc; }, {})
  ));
}

答案 1 :(得分:0)

您可以像这样执行单个更新:

ref.update({
  '/operations/products/foo': null,
  '/operations/products/bar': null
});

这将批量删除ref/operations/products中的foo和bar子项,同时保持所有其他子项不受影响。

但我想你仍然需要做一些循环来确定要更新的路径。