简体   繁体   中英

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;
@Component({
  moduleId: module.id,
  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() {
    this.getUsers();
  }

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

  onSelected(user: User) {
    this.selected.emit(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();
    });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM