【发布时间】:2020-03-19 07:29:47
【问题描述】:
我真的很想改进并了解如何更好地做到这一点。这段代码有效,但我相信这里有问题。思路如下:
1:我对 API 进行了第一次 HTTP 调用并获取了数据。
2:我使用的数据是 matchHistoryArr,它有一个包含 10 个“gameIds”的数组,我需要通过 forEach(loop) 将它们传递给 this.summ.getMatches(gameId) 并将它们推送到所需的新本地数组与另一个数组进行比较以对其进行排序(因为异步不会对其进行排序)所以在搜索了很多之后我可以像这样解决它。 (我将在代码中标记) 注意:这是我遇到大问题的地方,
3:现在我需要从其他端点获取更多数据,但我相信在继续之前我必须更好地订购代码。
Component.ts
onSubmit(){
** 1 **
this.summ.getSummoner(this.summoner.name,this.summoner.regionId)
.subscribe( (data:any) => {
let matchHistoryArr = data.matchHistory
let gameIdArray = matchHistoryArr.map( element => element.gameId)
const subscribers: Subscriber<any>[] = [];
const promiseMatchesArray = [];
** 2 **
matchHistoryArr.forEach( element => {
promiseMatchesArray.push( this.summ.getMatches(element.gameId).toPromise().then( match => {
subscribers.push(match)
}));
});
Promise.all(promiseMatchesArray).then( a =>{
if ( subscribers.length === matchHistoryArr.length ){
let arraySort = [];
arraySort = subscribers
let dataParticipants
let matchesArraySorted = arraySort.sort((a, b) => {
return gameIdArray.indexOf(a.gameId) - gameIdArray.indexOf(b.gameId);
});
this.matchesArray = matchesArraySorted
matchesArraySorted.forEach( x => {
dataParticipants = x.participants
});
if ( dataParticipants.length === 10 ){
this.dataParticipants = dataParticipants
}
}
});
this.matchHistory = matchHistoryArr
this.SummInfo = data.summonerdata;
});
}
Services.ts
export class SummonerService {
constructor( private http:HttpClient ) { }
summonerName
getSummoner(summonerName,regionId){
this.summonerName = summonerName
return this.http.get(`http://localhost:3000/summName/${summonerName}/${regionId}` )
.pipe(
map( (data:any) => data)
)};
getChampImage(champId){
return this.http.get(`https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champion-icons/${champId}.png`)
};
getMatches(gameId){
return this.http.get( `http://localhost:3000/match/${gameId}` )
.pipe(
map( (data:any) => this.uploadData(data))
)};
【问题讨论】:
标签: javascript angular typescript asynchronous