I'm having this issue on handling async calls on the ngOninit(). Basically I need to load a few things sequentially but I don't know how.
Here's the code:
import { Component, OnInit } from '@angular/core';
import { Match, Game, participantIdentities, player } from '../../models/match';
import { MatchService } from '../../services/match.service';
import { Global } from '../../services/global';
import { Observable } from 'rxjs';
@Component({
selector: 'app-players',
templateUrl: './players.component.html',
styleUrls: ['./players.component.css'],
providers: [MatchService]
})
export class PlayersComponent implements OnInit {
public matchs: Array<Match>;
public games: Array<Game>
public player: Array<player>;
public players: []
constructor(
private _matchService: MatchService
) {
this.games = []
this.player = []
}
ngOnInit(): void {
this.getMatchs()
}
getMatchs(){
this._matchService.getMatchs().subscribe(
response =>{
this.matchs = response.matchs;
console.log(this.matchs);
for(let i = 0; i<this.matchs.length; i++){
this.games[i] = this.matchs[i].game;
};
console.log(this.games)
}
,error=>{
console.log(<any>error)
}
);
}
getUsers(){
let accountId = [];
for(let i = 0; i < this.matchs.length; i++){
for(let x = 0; x < this.matchs[i].game.participantIdentities.length; x++){
if ( typeof(accountId.find(element=>element == this.matchs[i].game.participantIdentities[x].player.summonerName)) === "undefined"){
accountId.push(this.matchs[i].game.participantIdentities[x].player.summonerName)
this.player.push(this.matchs[i].game.participantIdentities[x].player)
}
}
}
console.log(this.player)
}
}
So as you can see, the data that getUsers() function is using, is coming from getMatchs(). if I execute both functions on ngOninit getUsers() it will throw an error, because the other one has not been done. Which makes sense. I could, of course, incorporate getUsers() into a button, but is not really my intention. I had this issue before and I would love resolve it properly. So the question is, how do I wait for it's completion in order to run the next function.