I have a class that, when initialized, retrieves data from the service and populates one of its properties, which is an array. The 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 that it is called before its constructor, and the ngOnInit () functions are executed (possibly because I use the async content from the Observables returned by the service). How can I guarantee that the constructor and init are fully executed before any function of my class is called from the outside?
export class BaseChoice implements PickAppraiser, OnInit {
weight = 0;
options = new Array<PickQuality>();
constructor(private championService: ChampionService) {}
ngOnInit() {
this.championService.getChampions()
.subscribe(champions => {
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[] {
this.championService.getChampions()
.subscribe(champions => {
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;
});
}
async select(), , , .