簡體   English   中英

如何在Angular訂閱firebase快照?

[英]How to subscribe to a firebase snapshot in Angular?

我正在嘗試獲取我的 firestore 數據庫 (v9) 的實時更新。 我在 Angular 中設置了一項服務,我想在其中對我的數據庫執行 onSnapshot 調用,但我不知道如何將此快照發送到我的組件並在組件中獲取實時更新。

這是我的服務

import { Injectable } from '@angular/core';
import { doc, getFirestore, onSnapshot } from 'firebase/firestore';

@Injectable({
    providedIn: 'root'
})
export class GameService {
    private db;

    constructor() {
        this.db = getFirestore();
    }

    async getGame(code: string) {
        const gameDoc = doc(this.db, 'games', code);
        return onSnapshot(gameDoc, (res) => res.data());
    }
}

這是我的組件:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GameService } from 'src/services/game.service';

@Component({
    selector: 'app-game',
    templateUrl: './game.component.html',
    styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
    game: any;

    constructor(private _activatedRoute: ActivatedRoute, private _gameService: GameService) { 
        this.getGame();
    }

    ngOnInit(): void {}

    async getGame() {
        this._activatedRoute.params.subscribe(async (parameters) => {
            let gamecode = parameters['code'];
            let snapshot = this._gameService.getGame(gamecode).then(res => {
                console.log(res.data());
            });
        })
    }
}

我嘗試了多種方法將數據從服務發送到我的組件,但似乎沒有任何效果。 關於如何做到這一點的任何想法? 非常感謝你

您可以創建一個 Observable(或其他類似結構)來執行此操作。 我建議從 RXJS 創建一個 BehaviorSubject。您可以在您的服務中創建一個屬性,例如:

public message$: BehaviorSubject<any> = new BehaviorSubject(null);

您在“onSnapshot”中使用它通過 message$ 屬性發送傳入數據,如下所示:

async getGame(code: string) {
    const gameDoc = doc(this.db, 'games', code);
    onSnapshot(gameDoc, (res) => this.message$.next(res.data()));
}

有了這個,您已經在將數據傳輸到快照中,現在您只需要在組件中訪問此可觀察對象即可接收所需的數據。 所以在你的組件中你可以這樣做:

private subject = new Subject<void>();
ngOnDestroy() {
  this.subject.next();
  this.subject.complete();
}
async getGame() {
    this._activatedRoute.params.subscribe(async (parameters) => {
        let gamecode = parameters['code'];
        this._gameService.getGame(gamecode);
        this._gameService.message$.pipe(takeUntil(this.subject))
         .subscribe((newData) => {
           // YOUR NEW DATA
         });    
    });
}

請注意 pipe “takeUntil” 來自 RXJS 並且是出於性能原因,以確保當您的組件被銷毀時您的 observable 也被銷毀(避免 memory 泄漏)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM