从Firebase数据库读取和显示数据 [英] reading and displaying data from a Firebase database
问题描述
我正在尝试从Firebase数据库检索数据,并将数据存储在我在课堂上定义的课程数组中.
I am trying to retreive data from a firebase database and store the data in a courses array i've defined in my class.
到目前为止,我已经知道了:
So far I've got :
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
courses:any[];
constructor(public afAuth: AngularFireAuth,private router:Router,private db:AngularFireDatabase) { }
ngOnInit() {
if(this.afAuth.auth.currentUser){
var ref = this.db.database.ref('/courses');
ref.on("value", this.gotData, function (error) {
console.log("Error: " + error.code);
});
}else{
this.router.navigate(['/login']);
}
}
gotData(data){
var x = data.val();
console.log(x);
this.courses = x; // >>>>>>>>>>>>>>>>> ISSUE HERE
}
}
但是我收到此错误消息:
However I am getting this error saying :
FIREBASE警告:用户回调引发了异常.TypeError:无法将属性课程"设置为空
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'courses' of null
和
错误TypeError:无法将属性"courses"设置为空
ERROR TypeError: Cannot set property 'courses' of null
我能够成功地控制台记录数据..但是我想存储这些数据.我该怎么办?
I am able to successfully console log the data.. but I want to store this data.. how can I do this?
推荐答案
错误消息告诉您 this
为空.为了确保保留它,将 gotData
定义为箭头函数:
The error message tells you that this
is null. To ensure that it is preserved, define gotData
as an arrow function:
gotData = (data) => {
this.courses = data.val();
}
这篇关于从Firebase数据库读取和显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!