Search code examples
angularfirebaseangularfire2

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?


Solution

  • 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