【发布时间】:2018-09-18 17:15:31
【问题描述】:
我正在阅读教程here 的“不相关组件:与服务共享数据”部分中有关如何在 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;
}
}
我有一个有机体实例,我们称之为有机体1。
我想将它添加到包含在 Population 模型中的个人数组中,并且我希望多个不相关的组件订阅人口 BehaviorSubject(我目前在我的 PopulationManagerService 中有 private currentPopulation = this.currentPopulationSource.asObservable(); 在我声明之后currentPopulationSource,正如我在教程中看到的那样)。
我不清楚将有机体1 添加到我的 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
});
目前返回未定义。
非常感谢您对此问题的任何帮助。
【问题讨论】:
-
问题中的噪音太大。你可以创建一个stackblitz吗?
标签: angular service rxjs behaviorsubject