I have a class that when initialized retrieves data from a service and popular one of its attributes, which is an array . This class has a function that sorts this array , filters and returns the result.
When instantiating an object of this class and calling this function I realized that the function is called before finishing the constructor and ngOnInit()
execution. I believe this happens because of the use of the asynchronous call to the service, which uses Observables .
How can I make sure this does not happen?
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;
}
}