Property undefinded when I get data from Firebase

3922 views angularjs
4

I have the following service:

@Injectable({
providedIn: 'root'
})
export class DatabaseService {
  private users: any[] = [];
  constructor(private db: AngularFireDatabase) { }

  getUsuarios(): any {
    this.db.database.ref('/users').once('value').then(
      data => {
        let users;
        usuarios = data.val() ? data.val() : {};
        console.log(users);
        return users;
      }
    );
  }
} 

But I need the data getted from Firebase Database in my HomeComponent.

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  users: any[] = [];
  constructor(private _databaseService: DatabaseService) {
    this.users = this._databaseService.getUsuarios();
    console.log(this.users);
  }

  ngOnInit() {
  }

}

When I show my console.log, this print undefined.

Can I get this data and print when I open my app?

answered question

1 Answer

5

You need to subscribe as follows,

this._databaseService.getUsuarios().subscribe((res)=>{
       this.users = res;
    },(err)=>{
      console.log(err);
});

posted this

Have an answer?

JD

Please login first before posting an answer.