代码之家  ›  专栏  ›  技术社区  ›  Atticus29

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

  •  1
  • Atticus29  · 技术社区  · 7 年前

    我正在阅读教程的“无关组件:与服务共享数据”部分中有关如何在Angular中的无关组件之间共享数据的内容 here .

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

    也就是说,我认为我的行为主体应该是这样的:

    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;
      }
    }
    

    private currentPopulation = this.currentPopulationSource.asObservable(); 在我的PopulationManagerService中,就在我声明currentpropulationsource之后,正如我在教程中看到的那样)。

    我不清楚将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
        });
    

    当前返回未定义。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ruben Vermeulen    7 年前

    如果我理解正确的话,您需要将一个新的有机体添加到位于种群对象内部的有机体列表中。这是在使用行为主题时发生的。

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

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

    注意,我只取流的一个值, take(1) . 这是因为当我们要计算新的有机体列表时,我们只需要当前的种群。这也可以防止不必要的内存泄漏。这个 take 操作员在一个事件过去后立即取消订阅流。

    对于您的用例来说,行为主题是否是一个好的选择很难用最少的信息来说明。