2
I have a class that when booting retrieves data from a service and popular one of its attributes, which is a array. This class has a function that sorts this array, filter and return 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 the ngOnInit()
. I believe this is due to the use of the asynchronous call to the service, which uses Observables.
How can I make sure this doesn’t 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;
}
}
The getChampions() method already returns an Observable, which I pick up on ngOnInit(). The problem is to ensure that onInit() runs before Choose(). I thought about solving this by calling getChampions() on Choose() as well, but it seems like a bad solution.
– Luis Paulo