如何从Firebase获取数据到服务,然后正确寻呼(AngularFire+ION 4)? [英] How to get data from Firebase to Service and then to Page correctly (Angularfire + ionic4)?

查看:0
本文介绍了如何从Firebase获取数据到服务,然后正确寻呼(AngularFire+ION 4)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过firebase.service中名为getData()的函数将数据从Firebase实时数据库获取到我的firebase.service

  • 我可以获取firebase.service中的数据,但无法加载 放到mypage页中。
  • 我可以在控制台中看到数据不是从Firebase读取的 页面加载时,但之后。

控制台日志:

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>

推荐答案

通常,数据是异步获取的,您的情况也不例外。在承诺完成之前,数据将不可用,因此在您的情况下,明智的做法是为您的服务方法中的数据返回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;
    });
  }

}

这篇关于如何从Firebase获取数据到服务,然后正确寻呼(AngularFire+ION 4)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆