I have a class that when initialized retrieves data from a service and populates one of its properties, which is an array. This same class has a function that sorts, filters and returns this array. When I instantiate an object of this class and call this function I realized it's called before its constructor and ngOnInit() functions are done (probably because I use async content from the Observables the service returns). How can I guarantee constructor and init have completely executed before any function of my class are called externally?
export class BaseChoice implements PickAppraiser, OnInit {
weight = 0;
options = new Array<PickQuality>();
constructor(private championService: ChampionService) {}
ngOnInit() {
// Iterates through the list of champions adding them to the current object
this.championService.getChampions()
.subscribe(champions => {
// Iterates through the list of champions adding them to the current object
Object.keys(champions).map(key => this.options.push(new PickQuality(champions[key], 0)))
})
}
choose(n?: number): PickQuality[] {
var sorted = this.options.sort((a, b) => a.score - b.score);
return sorted;
}
}
I also tried to do something like
choose(n?: number): PickQuality[] {
// Iterates through the list of champions adding them to the current object
this.championService.getChampions()
.subscribe(champions => {
// Iterates through the list of champions adding them to the current object
Object.keys(champions).map(key => this.options.push(new PickQuality(champions[key], 0)))
this.reevaluate(this.options);
var sorted = this.options.sort((a, b) => a.score - b.score);
var chosen;
if(n) chosen = sorted.slice(1, n);
else chosen = sorted.slice(1, 2);
return chosen;
});
}
where I run the async request inside the choose() method itself, but it won't let me do so, I assume because the return variable is not guaranteed to exist.