I was reading up on how to share data between unrelated components in Angular from the "Unrelated Components: Sharing Data with a Service" section of the tutorial here.
I see how this example works for the string they are trying to share across their components, but my data type is a little more complex:
Namely, I think my BehaviorSubject should look like this:
private currentPopulationSource: BehaviorSubject<Population> = new BehaviorSubject<Population>(new Population(new Array<Organism>()));
My population model is simply a container for an array of Organisms:
import { Organism } from './organism.model';
export class Population {
private individuals: any;
constructor(individuals: Organism[]){
this.individuals = individuals;
}
getIndividuals(){
return this.individuals;
}
}
I have an instance of Organism, let's call it organism1.
I'd like to add it to the individuals array wrapped in the Population model, and I'd like for multiple unrelated components to subscribe to the population BehaviorSubject (I currently have private currentPopulation = this.currentPopulationSource.asObservable(); in my PopulationManagerService right after my declaration of currentPopulationSource, as I saw in the tutorial).
It's unclear to me what the syntax would be to add organism1 to my currentPopulationSource (.next() doesn't seem to make sense here).
Perhaps BehaviorSubject isn't the most appropriate choice to make here if I want an ever-growing array to be the thing emitted? If there is a better option (ReplaySubject?), I don't quite know how to implement it.
My population manager service:
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
}
}
In my component:
let testIndividual: Organism = this.individualGenService.makeIndividual("green", "blue");
this.popManager.addOrganismToPopulation(testIndividual);
this.popManager.currentPopulation.subscribe(results =>{
console.log(results.getIndividuals()); //returns undefined
});
This is returning undefined currently.
Very grateful for any help with this issue.