我試圖通過firebase.service內的一個名為getData()的函式從Firebase Realtimedatabase獲取資料。
- 我可以在
firebase.service中獲得資料,但我不能將它們加載到mypage中。 到mypage頁面。 - 我可以在控制臺中看到,當頁面加載時,資料并沒有從Firebase中讀取。 讀取資料,而是在之后。
- 我在控制臺看到,資料不是在頁面加載時從Firebase讀取的,而是在之后。
控制臺日志:
mypage.page.ts:16 undefined
firebase.service.ts:20 這里是我的資料
我怎樣才能只讀一次我的資料并在我的頁面中顯示它們?使用服務?
mypage.page.ts代碼:
從'@angular/core'匯入 { Component, OnInit }。
從'.../firebase.service'中匯入 { FirebaseService }。
@Component({
selector: 'app-mypage',
templateUrl: './mypage.page.html',
styleUrls: ['./mypage.page.scss']。
})
export class MypagePage implements OnInit {
localData:字串。
建構式(private firebaseService: FirebaseService) {
this.firebaseService.getData(); //將資料加載到服務中去
this.localData = this.firebaseService.data;
console.log(this.localData)。
}
ngOnInit() {
}
}
firebase.service.ts代碼:
從'@angular/core'中匯入 { Injectable }。
import { AngularFireDatabase } from '@angular/fire/compat/database';
從'@angular/fire/compat/database/interfaces'中匯入 { DatabaseReference }。
@Injectable({
providedIn: 'root
})
出口類FirebaseService {
databaseRef:DatabaseReference。
data:字串。
constructor(private db: AngularFireDatabase) {
this.databaseRef = db.database.ref(); //Create databaseReference
}
getData(){
this.databaseRef.child('data').get().then((快照)=> {
如果(snapshot.existence()){
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>
uj5u.com熱心網友回復:
通常情況下,資料是以異步方式獲取的,你的情況也不例外。在承諾完成之前,資料是不可用的,所以在你的案例中,明智的做法是為你的服務方法中的資料回傳一個Promise:
getData(): Promise<any> {
return this.databaseRef.child('data').get().then((snapshot) => {
如果(snapshot.existence()) {
// 我認為你不需要再把資料保留在this.data中了
this.data = snapshot.val()。
console.log(this.data)。
回傳資料。
} else {
console.log('No data available')。
return null; // 或者回傳其他默認值,如[]或{}或""。
}
});
}
在你的組件中,你可以像這樣獲得資料:
export class MypagePage implements OnInit {
localData: string;
建構式(private firebaseService: FirebaseService){}。
ngOnInit() {
this.firebaseService.getData().then(data => {
this.localData = data;
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/330237.html
標籤:
