Angular 2 Observables - 对动作的空响应仍显示数组中的数据

时间:2017-01-16 23:53:06

标签: javascript angular firebase ionic2 angularfire2

我有这个功能,它聚合来自Firebase的一些用户数据,以构建“朋友请求”视图。在页面加载时,会显示正确的请求数。当我单击“接受”按钮时,更新正确的连接请求,然后再发出信号以再次运行此功能,因为用户已订阅它。唯一的问题是,一旦所有好友请求被接受,最后剩下的用户就会留在列表中,即使他们已被接受,也不会消失。

这是我用来获取请求的函数:

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}`)
            }))
        );
      });
  }

以下是我的Angular 2视图中的相关代码(使用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;
      })

    })
  }

我觉得我的观察能力有问题,这就是为什么会出现这个问题的原因。任何人都可以对此有所了解吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

我认为你在评论中钉了它。如果connectionKeys是一个空数组,则调用Observable.combineLatest是不合适的:

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}`)
  )
);