Angular 2 - Observables返回两次但几秒后......不确定为什么

时间:2017-01-20 18:44:41

标签: angular firebase firebase-realtime-database ionic2

我有一个Ionic 2应用程序,其功能是通过observables聚合一堆数据。数据回来了......除了它在第一次返回时并不总是完整。几秒钟后,我的数据再次返回,除了两个实例现在都填充了完整的数据。这真的很奇怪,我不确定是什么导致它。

这是我的功能:

getUserStories(data) {
    return this._af.database
      .object(`/social/users/${data.id}`)

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

        let connections = [];
        let connectionKeys = Object.keys(user.connections);

        return Observable.combineLatest(
          connectionKeys.map((connectionKey) => this._af.database
            .object(`/social/users/${connectionKey}`)
          ),
          (...connections) => {

            connectionKeys.forEach((connectionKey, index) => {

              this._af.database
                .object(`/social/user_stories_seen/${connectionKey}/${data.id}`).subscribe(data => {

                // Iterate over the connections and append the correct "last_seen" variable
                connections.forEach((connection, index) => {
                  if(connection.$key === connectionKey) {
                    connections[index]['last_seen'] = data;
                  }

                })
              });
            })
            return connections;
          });
      })
   }

以下是调用此功能的视图:

ionViewDidLoad() {

    // Get the user from storage and get all the connections
    this.storage.get('user').then(data => {

      //Get the user profile
      this._users.getUserStories({id: data.id}).subscribe(stories => {
        console.log('stories', stories);
      });
    })
}

还有其他人遇到过这个问题吗?

1 个答案:

答案 0 :(得分:1)

问题是你有内部的observable订阅然后更新连接的last_seen属性。

这些可观察对象不会被组合到您正在返回的可观察对象中,因此它们可以在 combineLatest运算符发出之后发出并更新连接

通过使用组合连接和最后看到的值的函数,可以简化实现:

getUserStories(data) {

  return this._af.database
    .object(`/social/users/${data.id}`)
    .switchMap((user) => {

      const getConnection = (connectionKey) => {
        return Observable.combineLatest(

          // Combine the connection and last-seen value:

          this._af.database
            .object(`/social/users/${connectionKey}`),
          this._af.database
            .object(`/social/user_stories_seen/${connectionKey}/${data.id}`),

          // Assign the last-seen value, but return the connection:

          (connection, seen) => {
            connection.last_seen = seen;
            return connection;
          }
        );
      };

      const connections = Object.keys(user.connections).map(getConnection);
      return Observable.combineLatest(...connections);
    });
}