How to ensure that a function that depends on ngOnInit runs after it?

0

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;
    }
}
    
asked by anonymous 06.02.2017 / 19:15

1 answer

0

In the case, I had a similar problem with the get method, I used a return ai the function should return which means that it waits for the answer before finishing the method

ngOnInit() {
// Iterates through the list of champions adding them to the current object
return 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)))
    })
}

The service method needs to be returned, I believe this will solve.

    
06.02.2017 / 19:39