Elias
Elias

Reputation: 357

Return value after snapshotChanges().subscribe in firebase list

I created the following function in order to get the data from a firebase table, including the record's key:

  fetchUsers() {
    this.firebase.list('users').snapshotChanges()
      .subscribe(res => {
        this.userList = [];
        res.forEach(element => {
          var user = element.payload.toJSON();
          user["$key"] = element.key;
          this.userList.push(user as User);
        });
      });
  }

how can i return the userList array when the function is called?

Upvotes: 1

Views: 1557

Answers (2)

Chrillewoodz
Chrillewoodz

Reputation: 28328

Don't subscribe and instead map to the value you want to return, this will return an Observable from fetchUsers which you can then subscribe to via this.fetchUsers.subscribe((...) => ...):

fetchUsers() {
    return this.firebase.list('users').snapshotChanges()
      .pipe(map((res) => {
        this.userList = [];
        res.forEach(element => {
          var user = element.payload.toJSON();
          user["$key"] = element.key;
          this.userList.push(user as User);
          return this.userList;
        });
      }));
  }

Upvotes: 0

Senal
Senal

Reputation: 1610

You can return an observable of an array and then subscribe to it.

fetchUsers(): Observable<User[]> {
  return this.firebase.list('users').snapshotChanges()
    .pipe(
      map(res => {
        return res.map(element => {
          let user = element.payload.toJSON();
          user["$key"] = element.key;
          return user as User;
        });
    }));
}

And then you can subscribe to this method from where ever you calling it.

this.usersSubscription = this.dataService.fetchUsers.subscribe(users=> {

   this.users = users;
});

Remember to unsusbscribe on onDestroy.

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

Checkout this working stackblitz

Upvotes: 1

Related Questions