Angular + Firebase firestore - 内部订阅文档在初始订阅时返回两个值
创始人
2024-10-14 12:30:58
0

在Angular和Firebase Firestore中,当您订阅一个文档时,它将立即返回一个初始值,然后在该文档发生更改时再次返回更新后的值。如果您想要在初始订阅时获取两个值,可以使用BehaviorSubject来实现。

首先,创建一个带有BehaviorSubject的服务,用于保存文档的当前值。在文档发生更改时,更新该BehaviorSubject。以下是一个示例服务代码:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable()
export class DocumentService {
  private documentSubject = new BehaviorSubject(null);
  document$ = this.documentSubject.asObservable();

  constructor(private firestore: AngularFirestore) { }

  subscribeToDocument(docId: string) {
    this.firestore.doc(`yourCollection/${docId}`).valueChanges().subscribe(doc => {
      this.documentSubject.next(doc);
    });
  }
}

在上述代码中,documentSubject是一个BehaviorSubjectdocument$是一个可观察对象,用于订阅文档的更改。subscribeToDocument()方法用于订阅文档,并在文档更改时更新documentSubject

接下来,在组件中使用该服务来订阅文档并获取两个值。以下是一个示例组件代码:

import { Component, OnInit } from '@angular/core';
import { DocumentService } from './document.service';

@Component({
  selector: 'app-document',
  template: `
    

{{ document.name }}

{{ document.description }}

`, providers: [DocumentService] }) export class DocumentComponent implements OnInit { document$; constructor(private documentService: DocumentService) { } ngOnInit() { this.documentService.subscribeToDocument('yourDocumentId'); this.document$ = this.documentService.document$; } }

在上述代码中,DocumentComponent通过DocumentService订阅了文档,并在ngOnInit生命周期钩子中将document$设置为DocumentService中的document$

在组件的模板中,使用async管道来订阅document$可观察对象,并在文档值存在时显示文档的名称和描述。

请注意,上述代码中的yourCollectionyourDocumentId应替换为您的Firestore集合和文档的实际名称。

相关内容

热门资讯

有消息称!雀姬手游透视辅助,禅... 有消息称!雀姬手游透视辅助,禅游游戏辅助(透视)器-一贯真的是有挂1、游戏颠覆性的策略玩法,独创攻略...
wepoker买脚本靠谱吗!w... wepoker买脚本靠谱吗!wepoker有透视功能吗(透视)软件-原来解迷存在有挂wepoker有...
经核实!微信四川熊猫辅助软件,... 经核实!微信四川熊猫辅助软件,川南休闲辅助(透视)软件-真是是有挂微信四川熊猫辅助软件辅助器是一种具...
hhpoker真的有透视吗!w... hhpoker真的有透视吗!wejoker内置辅助(透视)插件-一贯教你有挂1)hhpoker真的有...
受玩家影响!创思维激k透视软件... 受玩家影响!创思维激k透视软件,中至小程序破解(透视)技巧-果然有挂1、每一步都需要思考,不同水平的...
fishpoker透视底牌!p... fishpoker透视底牌!pokemmo脚本辅助器下载(透视)神器-真是科普是有挂1、在pokem...
受玩家影响!微信微乐小程序辅助... 受玩家影响!微信微乐小程序辅助器免费安装,九游破解辅助插件hhpoker(透视)技巧-果然真的有挂微...
wepoker网页版透视方法!... wepoker网页版透视方法!hhpoker破解工具(透视)插件-好像总结真的是有挂1、每一步都需要...
据权威媒体报道!新漫游大厅辅助... 据权威媒体报道!新漫游大厅辅助,阿拉斗牌辅助(透视)app-都是真的有挂1、玩家可以在新漫游大厅辅助...
pokemmo辅助器!hhpo... pokemmo辅助器!hhpoker是真的假的(透视)技巧-一贯分享真的有挂1)hhpoker是真的...