2016-11-10 29 views
4

目前,我陷入了Firebase Observable連接的問題。Firebase數據加入Observable

我真的不知道哪個是從不同對象獲取數據並將它們結合在一起的最佳方式。

我的數據結構:

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

conversations { 
    conversationid { 
     ... 
    } 
} 

現在我想要獲取當前用戶的所有對話。 爲了獲得當前用戶ID,我會訂閱AUTH可觀察到這樣的:

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個觀測量。我知道可以將它們嵌套在一起,但在我的項目中可能會發生多達5次。

是否可以在沒有嵌套的情況下獲得對話3個可觀察對象?

回答

5

你可以做這樣的事情:

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); }); 
+0

效果很好!謝謝。 – Orlandster