【问题标题】:Join two observable arrays together将两个可观察数组连接在一起
【发布时间】:2018-05-19 18:57:50
【问题描述】:
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 数据库中查询“线程”集合中的所有文档,其中字段 sellerIdbuyerId 等于它们的 userId。据我了解,AngularFire2 不允许您查询其中任何一个为真的所有文档;如果您链接他们的 .where() 方法,它将返回两者都为真的所有文档(在我的情况下为 0)。所以,我试图获取两个 Observable 数组并将它们组合成一个数组,以便实时告诉用户他们是否有未读消息。

我尝试了上面的代码(改编自答案here),它没有在订阅方法中运行任何东西。据我所知,我认为这是因为我的 observables 没有完成,因为我需要实时更新数据。有没有办法将两个仍在流式传输的可观察数组合并为一个,还是我必须想出另一种方法?

【问题讨论】:

  • 所以如果你分别订阅buyerThreads 和sellerThreads 你会得到我假设的值?
  • 是的,完全正确。他们自己记录值,但不是在我使用 forkJoin 之后。

标签: angular typescript rxjs ionic3 angularfire2


【解决方案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';

【讨论】:

  • 还想使用forkJoin?对Observable 数据使用first()take(1)。应该是valueChanges().first()
猜你喜欢
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 2021-01-03
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
相关资源
最近更新 更多