AngularFirestoreupdate方法会导致Observable触发两次
创始人
2024-10-24 21:32:17
0

在使用 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 也不会再次触发。

相关内容

热门资讯

重大来袭!微乐自建房辅助工具神... 重大来袭!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)器1、游戏颠覆性的策略玩法,独创...
带你了解!微信卡五星辅助器,微... 带你了解!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)方法1、带你了解!微信卡五星辅助器,...
一分钟揭秘!微乐家乡麻将自建房... 一分钟揭秘!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)插件1、下载好微乐家乡...
教程攻略!微乐自建房辅助工具,... 教程攻略!微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)app所有人都在同一条线上,像星星...
重大通报!微乐自建房辅助工具免... 重大通报!微乐自建房辅助工具免费app,微乐家乡麻将自建房辅助app(开挂自建房)教程1、重大通报!...
推荐一款!微信微乐自建房辅助工... 推荐一款!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)攻略进入游戏-大厅左侧-...
推荐一款!微乐自建房辅助工具神... 推荐一款!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)器1、金币登录送、破产送、升级送...
总算清楚!微信微乐自建房辅助工... 总算清楚!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)app1)微乐家乡麻将自...
重要通知!微乐自建房辅助工具神... 重要通知!微乐自建房辅助工具神器,微乐家乡麻将自建房辅助app(开挂自建房)方法1、在微乐家乡麻将自...
热点推荐!微信微乐自建房辅助工... 热点推荐!微信微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)app微信微乐自建房辅助工具能...