I am eager to enhance my skills and gain a better understanding of how to improve this code. While the current code is functioning, I suspect there may be an issue that needs addressing. Here's the concept:
1: Initially, I send the first HTTP request to the API and retrieve the data.
2: The key component here is the matchHistoryArr containing an array of 10 "gameIds." I need to iterate through these gameIds using a forEach loop to call this.summ.getMatches(gameId) for each gameId. The retrieved data must be stored in a new local array for comparison with another array since async operations do not provide sorted results by default. After much research and trial, I arrived at the solution presented within the code (marked for reference). Note: This section posed a significant challenge for me.
3: Next, I plan to fetch additional data from other endpoints; however, I feel it's necessary to reorganize the code structure before proceeding.
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))
)};