我正在尝试从 Firebase 数据库检索数据并将数据存储在我在类(class)中定义的类(class)数组中。
到目前为止我已经得到:
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
}
}
但是我收到此错误消息:
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'courses' of null
和
ERROR TypeError: Cannot set property 'courses' of null
我能够成功地控制台记录数据..但我想存储这些数据..我该怎么做?
最佳答案
错误消息告诉您this
为空。为了确保它被保留,请将 gotData
定义为箭头函数:
gotData = (data) => {
this.courses = data.val();
}
关于angular - 从 Firebase 数据库读取和显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030614/