AngularFire2 - 嵌套的 FirebaseObjectObservable 不会触发嵌套的 Firebase 调用
AngularFire2 - nested FirebaseObjectObservable won't fire a nested Firebase call
我有一个关于在 Firebase 中处理多对多关系的问题。基本上,我试图从我的 Firebase 数据中的多个路径构建一个用户配置文件对象。我已经尝试构建一个 returns 可观察对象的函数,然后更新该可观察对象中的数据作为嵌套可观察对象从 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;
});
}
嵌套的 observable 从未被调用,因为它从未被订阅 - observable 是惰性的。
你可以这样做,而不是:
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;
}
);
});
}
我有一个关于在 Firebase 中处理多对多关系的问题。基本上,我试图从我的 Firebase 数据中的多个路径构建一个用户配置文件对象。我已经尝试构建一个 returns 可观察对象的函数,然后更新该可观察对象中的数据作为嵌套可观察对象从 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;
});
}
嵌套的 observable 从未被调用,因为它从未被订阅 - observable 是惰性的。
你可以这样做,而不是:
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;
}
);
});
}