我有一个Ionic 2应用程序,它的功能是通过可观测值聚合一堆数据。数据回来了。。。只是第一次返回时并不总是完整的。几秒钟后,我的数据再次返回,只是两个实例现在都填充了完整的数据。这真的很奇怪,我不确定是什么原因造成的。
这是我的功能:
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);
});
})
}
有其他人遇到过这个问题吗?
问题是,您有内部可观察器在订阅并更新连接的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);
});
}