【问题标题】:Loop For on a BehaviorSubject stream在 BehaviorSubject 流上循环
【发布时间】:2018-02-12 19:03:57
【问题描述】:

我的线程变量包含 3 个不同的元素。我想创建一个迭代这三个对象的 For 循环。

threads: BehaviorSubject<{[key: string]: Thread }> = new BehaviorSubject({});

这是我的功能:

searchUser(): Observable<Thread> {
this.searchArrayThreads = [];
let element = document.getElementById('chat-window-input');

return this.threads.map((threadDictionary: {[key: string]: Thread}) => {
  for( let key in threadDictionary ) {
    console.log("key", threadDictionary[key]);
    if(threadDictionary[key].participants[0].name.startsWith(str)) {
      return threadDictionary[key];
    }
  }
});
}

此功能只能使用一次。在她的第一次通话中,她正在迭代 3 个元素。 然后它只迭代最后一个元素。

【问题讨论】:

    标签: angular typescript rxjs observable behaviorsubject


    【解决方案1】:

    因为这是BehaviourSubject 的本质,所以显示“当前”值或在本例中是推送给它的最后一个值(不知道推送它是否是正确的词,但这只是为了解释目的)。当您使用next() 方法向主题添加值时,它会显示最后一个值,在这种情况下它将显示最后一个值,因此,只循环一次(因为最后一个值它只是一个)。

    也许你应该阅读这篇关于 Rx.Subject() 的 Medium 文章,以更好地了解它们的工作原理和作用:

    Understanding rxjs BehaviorSubject, ReplaySubject and AsyncSubject

    在这种特殊情况下不知道您当前的要求,但也许您可以concat() 上一个和最后一个值,或者选择ReplaySubject()(将所有值发送给观察者)。

    大概是这样的(TS):

    const currentValues: Thread[] = this.threads.getValues(); // "current" values
    const newValues: Thread[] = newThreadsValues; //new Threads from somewhere
    
    this.threads.next(currentValues.concat(newValues);
    

    这适用于Thread 数组,但如果您只想添加一个Thread 实体,您应该选择Rx.ReplaySubject()

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 2019-08-27
      相关资源
      最近更新 更多