【发布时间】:2018-04-05 04:01:43
【问题描述】:
如何使用 AngularFire2 删除子集合?我的 component.ts 文件中有以下依赖项。 updateUser() 中的 id 由客户端操作传递。我在控制台中没有收到任何错误,但 firestore 也没有删除数据:
import { Component, OnInit} from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { expand, takeWhile, mergeMap, take } from 'rxjs/operators';
constructor(private afs: AngularFirestore) {}
//... @Component, export class, etc.
updateUser(role, id){
if(window.confirm('Are you sure?')){
const path = `users/${id}/roles`;
this.deleteCollection(path, 25);
// do other things...
}
}
deleteCollection(path: string, batchSize: number): Observable<any> {
const source = this.deleteBatch(path, batchSize)
// expand will call deleteBatch recursively until the collection is deleted
return source.pipe(
expand(val => this.deleteBatch(path, batchSize)),
takeWhile(val => val > 0)
)
}
// Deletes documents as batched transaction
private deleteBatch(path: string, batchSize: number): Observable<any> {
const colRef = this.afs.collection(path, ref => ref.orderBy('__name__').limit(batchSize) )
return colRef.snapshotChanges().pipe(
take(1),
mergeMap(snapshot => {
// Delete documents in a batch
const batch = this.afs.firestore.batch();
snapshot.forEach(doc => {
batch.delete(doc.payload.doc.ref);
});
return fromPromise( batch.commit() ).map(() => snapshot.length)
});
)
}
【问题讨论】:
标签: angular firebase google-cloud-firestore angularfire2