AngularFire2 - 嵌套的 FirebaseObjectObservable 不会触发嵌套的 Firebase 调用 [英] AngularFire2 - nested FirebaseObjectObservable won't fire a nested Firebase call
问题描述
我有一个关于在 Firebase 中处理多对多关系的问题.基本上,我试图从我的 Firebase 数据中的多个路径构建一个用户配置文件对象.我尝试构建一个返回 observable 的函数,然后更新该 observable 中的数据,因为嵌套的 observable 从 Firebase 获取数据.
I've got a question about dealing with working with many-to-many relationships in Firebase. Basically, I'm trying to build a user profile object from multiple paths inside of my Firebase data. I've tried building a function that returns an observable and then updates the data in that observable as a nested observable grabs data from Firebase.
问题是嵌套的 observable 永远不会被调用,据我所知.几个小时以来,我一直在反对这一点,但没有取得任何真正的成功.谁能告诉我我做错了什么?我觉得这是一个很常见的问题,可以解决.
The problem is that the nested observable doesn't ever get called, from what I can tell. I've been beating my head against this for hours without any real success. Can anyone tell what I'm doing wrong? I feel this is a pretty common problem that gets solved.
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 永远不会被调用,因为它永远不会订阅 - observables 是惰性的.
The nested observable is never called because it's never subscribed to - observables are lazy.
你可以这样做:
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;
}
);
});
}
这篇关于AngularFire2 - 嵌套的 FirebaseObjectObservable 不会触发嵌套的 Firebase 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!