angular - 2つのオブザーバブル配列を結合する
checkAllThreads() {
const userId = this.auth.getUser().uid;
const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
this.subscription = forkJoin(buyerThreads, sellerThreads)
.map(([bT, sT]) => [...bT, ...sT])
.subscribe(res=> {
console.log(res) //never console logs
//logic to iterate through array, look for unread threads goes here
});
}
私は AngularFire2 を使って、Firestore データベースの 'threads' コレクション内で、sellerId または buyerId が自分の userId と等しいすべてのドキュメントをクエリしています。私の理解では、AngularFire2 ではどちらか一方が真であるすべてのドキュメントをクエリすることはできません。.where() メソッドを連鎖させると、両方が真であるすべてのドキュメントが返されます(私の場合、これは 0 になります)。そのため、私は 2 つの Observable 配列を取得して、それらを 1 つの配列に結合し、ユーザーに未読メッセージがあるかどうかをリアルタイムで知らせようとしています。
私は上記のコード(ここでの回答から適応したもの)を試しましたが、subscribe メソッドでは何も実行されませんでした。私が思うに、それはおそらく私のオブザーバブルが完了していないからだと思います。リアルタイムでデータを更新する必要があるためです。二つのまだストリーミング中のオブザーバブル配列を一つに結合する方法はありますか、それとも別の方法を考える必要がありますか?
回答 #1
forkJoinの代わりにcombineLatestを使用してください。
だからそれはそうあるべきだ…
checkAllThreads() {
const userId = this.auth.getUser().uid;
const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
this.subscription = Observable.combineLatest(buyerThreads, sellerThreads)
.map(([bT, sT]) => [...bT, ...sT])
.subscribe(res=> {
console.log(res);
});
}
これら二行をインポートする必要があるかもしれません。
import 'rxjs/add/observable/combineLatest';
import { Observable } from 'rxjs/Observable';
