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集合和文档的实际名称。

相关内容

热门资讯

总算了解!wpk俱乐部辅助器,... 总算了解!wpk俱乐部辅助器,拱趴大菠萝挂,必赢方法(有挂教程);原来确实真的有挂(需添加指定薇13...
重大通报!wepoker免费脚... 重大通报!wepoker免费脚本咨询,hhpoker有作弊的吗,AI教程(有挂技巧);亲真的是有正版...
我来教教你!购买wepoker... 我来教教你!购买wepoker模拟器,aapoker如何设置胜率,AI教程(有挂教程)科技教程也叫必...
揭秘攻略!wepoker底牌透... 揭秘攻略!wepoker底牌透视,拱趴大菠萝挂怎么安装,微扑克教程(有挂透视)是一款可以让一直输的玩...
技术分享!wepoker辅助插... 技术分享!wepoker辅助插件功能,hhpoker到底可以作弊码,存在挂教程(有挂神器);最新版2...
一分钟揭秘!hhpkoer辅助... 一分钟揭秘!hhpkoer辅助挂是真的吗,wpk模拟器,详细教程(有挂透明);支持多人共享记分板与复...
指导大家!poker辅助器免费... 指导大家!poker辅助器免费安装,wepoker钻石怎么看底牌,切实教程(有挂攻略)1、点击下载安...
一分钟了解!hhpoker辅助... 一分钟了解!hhpoker辅助器,hh poker透视器下载,实用技巧(有挂攻略);《WPK辅助透视...
玩家亲测!aapoker免费透... 1、玩家亲测!aapoker免费透视脚本,wepoker有没有挂,曝光教程(有挂技巧)。2、aapo...
专业讨论!hhpoker脚本,... 专业讨论!hhpoker脚本,聚星ai辅助工具下载,科技教程(有挂技巧);小薇(透视辅助)致您一封信...