Taremeh
Taremeh

Reputation: 322

Firebase doesn't return value (Angular 2)

I try to retrieve data from my Firebase and it works, but JUST for console.log(). I can't return a value into a var...

As I'm working with Angular 2 & Typescript I have

a Service:

import {Injectable} from "angular2/core";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";
declare var Firebase: any;

@Injectable()
export class DataService {

    getAllData() {

        const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
        firebaseRef.on("value", function (snapshot) {
            console.log(snapshot.val()); // THIS WORKS!
            return snapshot.val(); // THIS DOES NOT WORK!
        });
    }

and a Component:

@Component({
templateUrl: 'templates/user.tpl.html',
providers: [DataService],
})

export class UserComponent implements OnInit{
userData: any;

constructor(private _dataService: DataService){}

ngOnInit():any {
    this.userData = this._dataService.getAllData(); 
    console.log(this.userData); // THIS DOES NOT WORK: UNDEFINED
}

If i run that, I get nothing for my userData var... And I can't figure how to fix that. I thought I would need an Observable but I failed, whatever I tried to do...

Can someone help?

Upvotes: 3

Views: 748

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202346

You need to wrap your call into an observable since Firebase is event-driven:

getAllData() {
  const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
  return Observable.create((observer) => {
    firebaseRef.on("value", function (snapshot) {
        console.log(snapshot.val());
        observer.next(snapshot.val());

    });
  });
}

This way you will be able to receive value by subscribing on the returned observable:

ngOnInit():any {
  this._dataService.getAllData().subscribe(data => {
    this.userData = data;
  }); 
}

Upvotes: 3

Related Questions