2016-11-11 58 views
1

我试过这个删除operations产品ID等于myProdID。 它删除了整个操作分支,而不仅仅是等于查询结果的分支。如何在一个步骤中删除列表查询的结果?

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

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

回答

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

上述函数将返回观察到的和删除会当呼叫者订阅它来执行。

如果你希望有函数返回一个承诺,你可以做这样的事情:

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; }, {}) 
)); 
} 
+0

它没有工作。我查看了更多关于mergeMap的内容,[https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35#mergemap](RxJS 5 Operators By Example)有一个例子,但我看不出与你有什么不同。 – Bogac

+0

'mergeMap'用于在'update'返回的promise被解析时完成observable。它以什么方式不起作用? – cartant

+0

对不起,我订阅了它。我对RxJS的东西不太满意。有什么办法可以回报承诺吗?我打算把它放在一个服务函数中,所以当它被调用时它会返回一个promise,并在调用组件中得到解决。 – Bogac

0

你可以像这样执行一个更新:

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

这将批量,同时保持所有其他的孩子从不变删除ref/operations/products的foo和酒吧的孩子。

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

相关问题