2

I've been making an Angular2 app with Angularfire2. I'm stuck in a problem about FirebaseListObservable when retrieving data from Firebase. Here is my code.

this.requests = this._af.database.list('/requests');

Soon after this, I logged this variable.

console.log(this.requests);

Then I got an undefined one, but I wanted to wait this request's response because this.requests was always undefined in this code. I'd like you to teach me how to wait the result of firebase requests. Sorry about my poor English.

taku845
  • 133
  • 1
  • 3
  • 11

2 Answers2

2

Since retrieving data from Firebase is asynchronous, you need to "subscribe" to the event when the requested data comes in. It is important to close (unsubscribe) the connection after it is not used anymore to avoid further problems. This can be achieved with the following code:

this.requests = this._af.database.list('/requests')
  .subscribe(data => {
    data.forEach(obj => {
      console.log(obj.$key);
      console.log(obj.$value);
    });
    this.requests.unsubscribe();
});

If you want to preserve the connection, because you are updating your data, you should omit this.requests.unsubscribe(); and rather put

ngOnDestroy(){
  this.requests.unsubscribe();
}

in your component, so the connection gets closed when your component is destroyed.

Community
  • 1
  • 1
Niklas
  • 121
  • 1
  • 6
  • Thank you for your commenting. I didn't know this unsubscribe method, so I'm gonna learn about how I can use it to close the connection. – taku845 Nov 30 '16 at 05:06
0

The list method returns an Observable so you can subscribe to it to get the returned requests.

  export class AppComponent {
    requests: FirebaseListObservable<any[]>;

    constructor(private af: AngularFire) {

    }

    ngOnInit() {
      this.requests = this.af.database.list('/requests');

      this.requests.subscribe(
        (requests) => {
          console.log(requests)
        },
        err => console.log(err)
      );
    }
  }
JayChase
  • 11,174
  • 2
  • 43
  • 52
  • Thank you, and I have an additional question. Is it better to call the request in ngOnInit than constructor? I learned constructor is called before ngOnInit. I always cannot decide which to use. If you like, I hope you'll answer this. – taku845 Nov 30 '16 at 05:03
  • @taku. It's good practice, see [this](http://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit) thread for more. – JayChase Nov 30 '16 at 05:19
  • Thanks! I will see it. – taku845 Nov 30 '16 at 05:43