Reputation: 3245
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 WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'courses' of null
and
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?
Upvotes: 2
Views: 93
Reputation: 73731
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();
}
Upvotes: 1