在使用 AngularFirestore 的 update 方法更新文档时,可能会遇到 Observable 多次触发的问题。这是因为 update 方法会在文档更新成功后返回一个新的文档快照,而 Angular 的 Observable 检测到这个新值后会重新触发一次。为了避免这种情况,可以使用 take(1) 或 first() 操作符来只接收 Observable 的第一个值,例如:
import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
interface Item {
name: string;
description: string;
}
@Component({
selector: 'app-update-item',
template: `
`,
})
export class UpdateItemComponent {
private itemDoc: AngularFirestoreDocument- ;
item: Observable
- ;
newName: string;
newDescription: string;
constructor(private afs: AngularFirestore) {}
updateItem() {
this.itemDoc.update({ name: this.newName, description: this.newDescription })
.then(() => console.log('Item updated successfully'))
.catch((error) => console.log('Error updating item: ', error));
// 使用 take(1) 或 first() 操作符只接收第一个触发值
this.item.pipe(take(1)).subscribe((data) => console.log('Item snapshot after update: ', data));
}
}
在上述代码中,我们在 updateItem() 方法中使用了 take(1) 操作符来只接收 Observable 的第一个值。这样即使 update 方法返回了新的文档快照,Observable 也不会再次触发。