Firebase 数据加入 Observable

Firebase data join with Observable

目前,我遇到了 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); });