将元素添加到 Angular2+ 中的数组的 rxjs BehaviorSubject 或 Subject

Add elements to rxjs BehaviorSubject or Subject of an array in Angular2+

我正在阅读教程 here 的 "Unrelated Components: Sharing Data with a Service" 部分,了解如何在 Angular 中的不相关组件之间共享数据。

我看到了这个示例如何处理他们试图在其组件之间共享的字符串,但我的数据类型有点复杂:

也就是说,我认为我的 BehaviorSubject 应该是这样的:

private currentPopulationSource: BehaviorSubject<Population> = new BehaviorSubject<Population>(new Population(new Array<Organism>()));

我的种群模型只是一组生物体的容器:

import { Organism } from './organism.model';

export class Population {
  private individuals: any;
  constructor(individuals: Organism[]){
     this.individuals = individuals;
  }

  getIndividuals(){
    return this.individuals;
  }
}

我有一个 Organism 实例,我们称它为 organism1。

我想将它添加到包含在 Population 模型中的 individuals 数组中,并且我希望多个不相关的组件订阅 population BehaviorSubject(我目前在我的 PopulationManagerService 中有 private currentPopulation = this.currentPopulationSource.asObservable();在我声明 currentPopulationSource 之后,正如我在教程中看到的那样)。

我不清楚将 organism1 添加到我的 currentPopulationSource 的语法是什么(.next() 在这里似乎没有意义)。

如果我想让一个不断增长的数组成为发出的东西,也许在这里 BehaviorSubject 不是最合适的选择?如果有更好的选择(ReplaySubject?),我不太清楚如何实现。

我的人口管理服务:

import { Injectable } from '@angular/core';
import { Organism } from './organism.model';
import { Population } from './population.model';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PopulationManagerService {
  private currentPopulationSource: BehaviorSubject<Population> = new BehaviorSubject<Population>(new Population(new Array<Organism>()));
  currentPopulation = this.currentPopulationSource.asObservable();
  constructor() { }

  addOrganismToPopulation(organism: Organism){
    this.currentPopulationSource.next(new Population(new Array<Organism>(organism))); //This does not work
    // this.currentPopulation.getIndividuals().push(organism); //This did not work either, because currentPopulation is of type Observable<Population> rather than of type Population
  }
}

在我的组件中:

let testIndividual: Organism = this.individualGenService.makeIndividual("green", "blue");
    this.popManager.addOrganismToPopulation(testIndividual);
    this.popManager.currentPopulation.subscribe(results =>{
      console.log(results.getIndividuals()); //returns undefined
    });

当前返回未定义。

非常感谢对此问题的任何帮助。

如果我没理解错的话,您想将一个新生物体添加到种群对象内的生物体列表中。这在使用行为主题时。

在您的示例中,您可以执行以下操作。

addOrganismToPopulation(organism: Organism){
    this.currentPopulationSource
        .pipe(take(1))
        .subscribe((population: Population) => {
            this.currentPopulationSource.next(
                new Population([...population.getIndividuals(), organism]))
            )
        });
  }

那么我们在这里做什么。要将新生物体添加到当前种群中,我们需要知道生物体列表。因此,我们订阅了包含人口的可观察对象。在订阅中,我们创建了一个新的 population 实例。在创建新实例时,我们创建了一系列已知生物和新生物。然后我们将 new/updated 人口放到流中。

请注意,我只获取流的一个值,take(1)。这是因为当我们想要计算新的生物列表时,我们只需要当前的种群。这也可以防止不必要的内存泄漏。 take 运算符在一个事件过去后取消订阅流。

用最少的信息很难说行为主题是否适合您的用例。