我有一个关于处理Firebase中多对多关系的问题。基本上,我正在尝试从Firebase数据中的多个路径构建用户配置文件对象。我已经尝试构建一个返回observable的函数,然后更新该observable中的数据,因为嵌套的observable从Firebase获取数据。
问题在于,根据我所知,嵌套的observable永远不会被调用。几个小时以来,我一直在打我的头,没有任何真正的成功。谁能说出我做错了什么?我觉得这是一个很常见的问题,可以解决。
public getUserProfile(data) {
return this._af.database.object(`/social/users/${data.id}`).map((user) => {
for ( let vidKey in user.videos) {
// Once the code hits this line, it never fires at all :(
this._af.database.object(`/social/videos/${vidKey}`).map((video) => {
user.videos[vidKey] = video;
});
}
return user;
});
}
答案 0 :(得分:5)
永远不会调用嵌套的observable,因为它永远不会被订阅 - observables是懒惰的。
你可以做这样的事情,而不是:
public getUserProfile(data) {
return this._af.database
.object(`/social/users/${data.id}`)
// Switch to the joined observable
.switchMap((user) => {
let vidKeys = Object.keys(user.videos);
// Use forkJoin to join the video observables. The observables will
// need to complete, so first is used. And use forkJoin's selector to
// map the videos to the user and then return the user.
return Observable.forkJoin(
vidKeys.map((vidKey) => this._af.database
.object(`/social/videos/${vidKey}`)
.first()
),
(...videos) => {
vidKeys.forEach((vidKey, index) => { user.videos[vidKey] = videos[index] });
return user;
}
);
});
}