【发布时间】:2020-08-23 12:17:04
【问题描述】:
我在处理 ngOninit() 上的异步调用时遇到了这个问题。基本上我需要按顺序加载一些东西,但我不知道如何。
代码如下:
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)
}
}
如您所见,getUsers() 函数使用的数据来自 getMatchs()。如果我在 ngOninit getUsers() 上执行这两个函数,它会抛出一个错误,因为另一个还没有完成。这是有道理的。当然,我可以将 getUsers() 合并到一个按钮中,但这并不是我的真正意图。我以前遇到过这个问题,我很想妥善解决它。所以问题是,我如何等待它完成才能运行下一个函数。
【问题讨论】:
标签: angular typescript asynchronous httprequest