3

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?

1 Answer 1

3

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;
  }); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It now works but somehow, the values won't display in my input fields (as default values) of my formbuilder: codeshare.io/XSAzO
In fact the data is loaded asynchronously. So it's not there when the form is created. I would update the input later (within the subscribe callback) like this: this.userForm.controls.username.updateValue(this.userData.username);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.