它比一行代码多一点,但你可以这样做:
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; }, {})
));
}
它没有工作。我查看了更多关于mergeMap的内容,[https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35#mergemap](RxJS 5 Operators By Example)有一个例子,但我看不出与你有什么不同。 – Bogac
'mergeMap'用于在'update'返回的promise被解析时完成observable。它以什么方式不起作用? – cartant
对不起,我订阅了它。我对RxJS的东西不太满意。有什么办法可以回报承诺吗?我打算把它放在一个服务函数中,所以当它被调用时它会返回一个promise,并在调用组件中得到解决。 – Bogac