Fish-Guts
Fish-Guts

Reputation: 336

Data not ready when needed

I need to load some data from the server before further processing. So have I have this function:

async load() {
    await this.reloadClients()
    this.findTimeSheets();
}

findTimeSheets() {
    for (const client of this.clients) {
        console.log('Client: ' + client.lastName);
    }      
}

This function gets called when clicking a button on the component.

I need the function this.timeSheets to wait until this.reloadClients is done processing, so the data is ready. This is the the reload function, it should load a list of clients and store it in this.clients:

reloadClients() {
    this.clientService.search({
        page: '0',
        query: 'assigner.id:' + this.selectedAssigner.id,
        size: '250',
        sort: ''})
       .subscribe((res: HttpResponse<Client[]>) => { this.clients = res.body; this.init(res.body); }, (res: HttpErrorResponse) => this.onError(res.message));
}

What happens now is that I need to click the button twice to get the correct data. So the loop in findTimeSheets() works after the second click (printing data to console).

My approach was to use await, but somehow this doesn't work.

As I'm new to Angular, I need some help resolving this.

Upvotes: 0

Views: 123

Answers (1)

basarat
basarat

Reputation: 276161

You have await this.reloadClients() However the function reloadClients is not async. So the await is useless.

Fix

Make reloadClients async e.g.

async reloadClients() {
    await this.clientService.search({
        page: '0',
        query: 'assigner.id:' + this.selectedAssigner.id,
        size: '250',
        sort: ''})
       .subscribe((res: HttpResponse<Client[]>) => { this.clients = res.body; this.init(res.body); }, (res: HttpErrorResponse) => this.onError(res.message))
       .toPromise();
}

Upvotes: 0

Related Questions