它比一行代碼多一點,但你可以這樣做:
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