该问题是由于使用 AngularFirestore 的 update 方法更新文档时,会自动导致 Observable 两次触发造成的。这是因为 AngularFire 库的 DocumentReference 类使用 Object.assign 来更新文档,但该方法会将目标对象的属性合并到原始对象中,导致 Observable 两次触发。
为了解决这个问题,我们可以使用 AngularFire 的 set 方法代替 update 方法来更新文档。 但是,这个方法需要我们确切地传递整个文档对象,而不仅仅是更新其中一个值。为了保留原始文档值,我们应该将原始文档对象与新的更新值合并,然后将合并后的对象传递给 set 方法。
以下是示例代码:
import { Injectable } from '@angular/core';
import { AngularFirestore, DocumentReference } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private firestore: AngularFirestore) {}
updateDocumentValue(
collectionPath: string,
documentId: string,
update: any
): Observable {
// Get a reference to the document
const docRef = this.firestore.collection(collectionPath).doc(documentId);
// Merge the original document with the update value
const updateWithOriginal = docRef.valueChanges().pipe(
take(1),
mergeMap(doc => Object.assign({}, doc, update))
);
// Call set with the merged value
return updateWithOriginal.pipe(mergeMap(mergedValue => docRef.set(mergedValue)));
}
}
使用此方法,我们可以更新文档而不会导致 Observable 两次触发。