Padmanaban Gokula Padmanaban Gokula - 6 months ago 36
Javascript Question

angular2 saving response from firebase to a model

Thanks a lot for reading this question. Have been struggling for a while, will be great if someone point out what I'm doing wrong here.

I'm getting result from firebase and trying to save it in the User Model, but I'm getting this error "Uncaught TypeError: Cannot set property 'users' of null".

import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { User } from '../user.ts';
import { UserComponent } from './user.component';
declare var firebase: any;
selector: 'trafford-user-list',
templateUrl: 'user-list.component.html',
styleUrls: ['user-list.component.css'],
directives: [ UserComponent ]
export class UserListComponent implements OnInit {
private users: User[] = [{ name: 'sosk', email: 'dfdok', password: 'asdf'}];
private user: User;
@Output() selected = new EventEmitter<User>();
constructor() { }

ngOnInit() {

getUsers() {
firebase.database().ref('accounts').on('value', function(snapshot) {
this.users = snapshot.val();

onSelected(user: User) {


When I try to write the response in the console its working. But this.users don't have any scope inside that firebase callback. I'm very new to angular any help would be appreciated.


Use arrow function (=>) to preserve scope

  getUsers() {
    firebase.database().ref('accounts').on('value', (snapshot) => {
      this.users = snapshot.val();