【发布时间】:2021-11-13 16:28:15
【问题描述】:
我正在尝试通过 firebase.service 内部名为 getData() 的函数将数据从 Firebase Realtimedatabase 获取到我的 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>
【问题讨论】:
标签: angular ionic-framework firebase-realtime-database angularfire angular-services