2016-11-10 5 views
4

現在、Firebase Observable結合に問題があります。ObservableとのFirebaseデータの結合

どのオブジェクトが異なるオブジェクトからデータを取得して一緒に結合するのが最適な方法であるかわかりません。

マイデータ構造:

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

conversations { 
    conversationid { 
     ... 
    } 
} 

は、今私は、現在のユーザーのすべての会話を取得したいです。私は会話のIDを取得するために、ユーザの子オブジェクトが必要

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回起こる可能性があります。

オブザーバブルを入れ子にすることなく会話することは可能ですか?

答えて

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

作品も! THX。 – Orlandster

関連する問題