How to ensure that a ngOnInit-dependent function is executed after it?

Asked

Viewed 739 times

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;
    }
}

2 answers

1


In this case, I have had a similar problem with the get method, I used a Return so the function should return what means makes it wait 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 method of service needs to have a return, I believe this solves.

  • 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.

1

You can guarantee execution using Promise but it won’t stay anymore Asynchronous.

const promiseChampion = new Promise(resolve => { 
resolve(this.championService.getChampions().toPromise()) 
});

promiseChampion.then(value => { 
//código que deverá ser executado caso de certo 
// value trás o valor que sua api deve retornar
});

promiseChampion.catch(error => {
// caso de erro vai vir parar aqui
// error trás o erro ocorrido
});

See if this is what you need.

In case you put Promise inside the ngOnInit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.