2

I have a problem with my Angular2 Type Script code. I'm trying to access Questions from a Firebase Database, which I am doing by subscribing to a FirebaseListObserver:

this.af.list('/questions').subscribe( val => {
     this.questions = val
     console.log(this.questions) // works
})
console.log(this.questions) // displays undefined

I dont know how to wait for the subscription to get a value, though, before running a function which depends on this.questions.

I tried to use async/await, but also didn't wait for the subscription to get a value.

I also tried to subscribe inside a promise, but also returned an empty array.

Lucas Mähn
  • 736
  • 2
  • 6
  • 19

1 Answers1

0

You can either run the function from within the subscribe callback or you can turn questions into a setter/getter:

private _questions = [];

set questions(questions) {
  this._questions = questions;

  // React to questions changes here
}

get questions() {
 return this._questions;
}

Which will act kinda like a watcher if you're familiar with the early version of angular. So in the set function you can check if questions has a value and react to it, calling whatever function you need.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • I already tried to call the function in the subscribe callback, but it seems to work inconsistent, so sometimes it works, but sometimes it returns undefined. I have the same problem with the setter/getter. – Lucas Mähn Jul 17 '17 at 12:30
  • @LucasMähn That shouldn't happen, can you add a `.filter(data => data !== undefined)` before the subscribe and see if that helps? – Chrillewoodz Jul 18 '17 at 06:37