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 数组并将它们合并到一个数组中,以便实时告知用户他们是否有未读消息。
我尝试了上面的代码(改编自一个答案 here ),它没有在订阅方法中运行任何东西。据我所知,我认为这是因为我的可观察对象尚未完成,因为我需要实时更新数据。有什么方法可以将两个仍在流式传输的可观察数组合并为一个,还是我必须想出另一种方法?
最佳答案
使用 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';
关于angular - 将两个可观察数组连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665071/