我有一个函数,它从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;
})
})
}
我觉得我的可观察性出了问题,这就是为什么会发生这个问题。也许有人能对此有所了解吗?提前感谢!
我想你在评论中已经把它钉住了。如果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}`)
)
);