psj01
psj01

Reputation: 3245

reading and displaying data from a Firebase database

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

Answers (2)

Martin Parenteau
Martin Parenteau

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

Sajeetharan
Sajeetharan

Reputation: 222582

You need to initialize the courses

 courses:any[] = [];

Upvotes: 1

Related Questions