简体   繁体   中英

Angular 2 Observables - Empty response on action still shows data in array

I have this function that aggregates some user data from Firebase in order to build a "friend request" view. On page load, the correct number of requests show up. When I click an "Accept" button, the correct connection request gets updated which then signals to run this function again, since the user is subscribed to it. The only problem is that once all of the friend requests are accepted, the last remaining user stays in the list and won't go away, even though they have already been accepted.

Here is the function I'm using to get the requests:

getConnectionRequests(userId) {

    return this._af.database
      .object(`/social/user_connection_requests/${userId}`)

      // Switch to the joined observable
      .switchMap((connections) => {

        // Delete the properties that will throw errors when requesting
        // the convo keys
        delete connections['$key'];
        delete connections['$exists'];

        // Get an array of keys from the object returned from Firebase
        let connectionKeys = Object.keys(connections);

        // Iterate through the connection keys and remove
        // any that have already been accepted

        connectionKeys = connectionKeys.filter(connectionKey => {

          if(!connections[connectionKey].accepted) {
            return connectionKey;
          }
        })

        return Observable.combineLatest(
          connectionKeys.map((connectionKey => {

              return this._af.database.object(`/social/users/${connectionKey}`)
            }))
        );
      });
  }

And here is the relevant code in my Angular 2 view (using Ionic 2):

ionViewDidLoad() {

    // Get current user (via local storage) and get their pending requests
    this.storage.get('user').then(user => {
      this._connections.getConnectionRequests(user.id).subscribe(requests => {

        this.requests = requests;
      })

    })
  }

I feel I'm doing something wrong with my observable and that's why this issue is happening. Can anyone shed some light on this perhaps? Thanks in advance!

I think you nailed it in your comment. If connectionKeys is an empty array calling Observable.combineLatest is not appropriate:

import 'rxjs/add/observable/of';

if (connectionKeys.length === 0) {
  return Observable.of([]);
}
return connectionKeyObservable.combineLatest(
  connectionKeys.map(connectionKey =>
    this._af.database.object(`/social/users/${connectionKey}`)
  )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM