如何从 Firebase 获取数据到服务,然后正确地到页面(Angularfire + ionic4)?

How to get data from Firebase to Service and then to Page correctly (Angularfire + ionic4)?

我正在尝试通过 firebase.service.

中名为 getData() 的函数将数据从 Firebase Realtimedatabase 获取到我的 firebase.service

控制台日志:

mypage.page.ts:16 undefined
firebase.service.ts:20 here is my data

如何只读取一次我的数据并在我的页面中显示它们?使用服务?


mypage.page.ts代码:

import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../firebase.service';

@Component({
  selector: 'app-mypage',
  templateUrl: './mypage.page.html',
  styleUrls: ['./mypage.page.scss'],
})
export class MypagePage implements OnInit {
  localData: string;

  constructor(private firebaseService: FirebaseService) {
    this.firebaseService.getData(); //Load data INTO the service

    this.localData = this.firebaseService.data;
    console.log(this.localData);
  }

  ngOnInit() {
  }

}

firebase.service.ts代码:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { DatabaseReference } from '@angular/fire/compat/database/interfaces';

@Injectable({
  providedIn: 'root'
})
export class FirebaseService {
  databaseRef: DatabaseReference;
  data: string;

  constructor(private db: AngularFireDatabase) {
    this.databaseRef = db.database.ref(); //Create databaseReference
  }

  getData(){
    this.databaseRef.child('data').get().then((snapshot) => {
      if (snapshot.exists()) {
        this.data = snapshot.val();
        console.log(this.data);
      } else {
        console.log('No data available');
      }
    });
  }
}

mypage.page.html代码:

<ion-header>
  <ion-toolbar>
    <ion-title>mypage</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
<ion-label>{{ localData }}</ion-label>
</ion-content>

通常,数据是异步获取的,您的情况也不例外。在承诺完成之前数据将不可用,因此在您的情况下,明智的做法是 return 一个 Promise 用于您的服务方法中的数据:

  getData(): Promise<any> {
    return this.databaseRef.child('data').get().then((snapshot) => {
      if (snapshot.exists()) {
        // I don't think you need to keep the data in this.data anymore
        this.data = snapshot.val();
        console.log(this.data);
        return data;
      } else {
        console.log('No data available');
        return null; // or return another default value, like [] or {} or "";
      }
    });
  }

在你的组件中,你可以这样获取数据:

export class MypagePage implements OnInit {
  localData: string;

  constructor(private firebaseService: FirebaseService) {}

  ngOnInit() {
    this.firebaseService.getData().then(data => {
       this.localData = data;
    });
  }

}