我正在阅读本教程的“不相关组件:与服务共享数据”部分,了解如何在 Angular 中的不相关组件之间共享数据here https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/.
我看到这个示例如何适用于他们试图在组件之间共享的字符串,但我的数据类型有点复杂:
也就是说,我认为我的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 模型中的个体数组中,并且我希望多个不相关的组件订阅populationBehaviorSubject(我目前有private currentPopulation = this.currentPopulationSource.asObservable();
在我的 PopulationManagerService 中,就在我声明 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
});
当前返回未定义。
非常感谢您对这个问题的任何帮助。