Firebase 数据与 Observable 连接

标签 firebase firebase-realtime-database rxjs observable angularfire2

目前,我遇到了 Firebase Observable 连接的问题。

我真的不知道从不同对象获取数据并将它们连接在一起的最佳方法是什么。

我的数据结构:

users {
    userid1 {
        conversationid: id
        ...
    },
    userid2 {
       ...
    }
}

conversations {
    conversationid {
        ...
    }
}

现在我想获取当前用户的所有对话。
要获取当前用户 ID,我将像这样订阅 auth Observable:
 this.af.auth.subscribe(auth => {
    console.log(auth.uid);
 });

接下来我需要用户的子对象来获取对话 ID。我这样做:
 //needs the userid from Observable on top 
 this.af.database.object('/users/' + auth.uid)
     .map(
         user => {
             console.log(user.conversationid);
         }
      )
      .subscribe();

对话也是如此:
//needs the conversationid from the second Observable 
this.af.database.list('/conversations/' + user.conversationid)
    .subscribe();

如您所见,有 3 个 Observable。我知道可以嵌套它们,但在我的项目中这种情况最多可能发生 5 次。

是否可以在不嵌套 3 个 Observable 的情况下进行对话?

最佳答案

你可以这样做:

let combined = this.af.auth

    // Filter out unauthenticated states

    .filter(Boolean)

    // Switch to an observable that emits the user.

    .switchMap((auth) => this.af.database.object('/users/' + auth.uid))

    // Switch to an observable that emits the conversation and combine it
    // with the user.

    .switchMap((user) => this.af.database
        .list('/conversations/' + user.conversationid)
        .map((conversation) => ({ user, conversation }))
    );

// The resultant observable will emit objects that have user and
// conversation properties.

combined.subscribe((value) => { console.log(value); });

关于Firebase 数据与 Observable 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537453/

相关文章:

angular - 为什么@angular\router 参数中的 ActivatedRoute 是可观察的?

javascript - 服务人员 notificationclick 事件没有聚焦或在选项卡中打开我的网站

Firebase 浏览器 key API 限制

swift - 使用 swift 从另一个函数访问闭包内的变量

swift - 当前用户 UID 与身份验证 UID 不同吗?

typescript - 我如何解决 TypeScript 2.4 和 RxJS 5.x 中的这个 "Subject incorrectly extends Observable"错误?

javascript - 从 Firebase 存储中读取文件的值/内容

firebase - 您如何在 Unity 中测试 Firebase 动态链接?

javascript - 如何在 JavaScript 中将 JSON 键保留为字符串

angular - Observable - 开始有条件地发出