angular - รวมอาเรย์ observable สองตัวเข้าด้วยกัน
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) ดังนั้นฉันจึงพยายามที่จะได้ Observable arrays สองอันและรวมพวกมันเป็น array เดียวเพื่อแจ้งผู้ใช้แบบเรียลไทม์ว่าพวกเขามีข้อความที่ยังไม่ได้อ่านหรือไม่
ฉันลองใช้โค้ดด้านบน (ดัดแปลงมาจากคำตอบที่นี่) ซึ่งไม่ได้รันอะไรในเมธอด subscribe จากที่ฉันดู ฉันคิดว่าน่าจะเป็นเพราะ observables ของฉันยังไม่เสร็จสมบูรณ์ เพราะฉันต้องการให้ข้อมูลอัปเดตแบบเรียลไทม์ มีวิธีใดที่จะรวมอาร์เรย์ observable สองตัวที่ยังสตรีมอยู่เข้าด้วยกันเป็นตัวเดียวได้ไหม หรือฉันจะต้องหาวิธีอื่น?
คำตอบ #1
ใช้ combineLatest แทน forkJoin
ดังนั้นมันควรจะ...
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';
