【发布时间】:2020-07-03 10:26:03
【问题描述】:
我想要达到的目标: 从 component.ts 调用 this.getMatches 服务,在 this.getMatches 中我必须进行一些 API 调用并处理我得到的数据 在它被推送到数组之前
我做了什么: 1:函数运行并将“gameId”作为参数发送给函数this.getmatches。我得到了每场比赛的数组,其中包含我推送到每场比赛的所有数据 2:经过多次尝试,我找到了一个有效的方法,但是返回数组时失败了
问题: 有时它会返回相同的匹配项,我注意到当我添加“swtichmap”运算符时会发生这种情况。
Services.ts
@Injectable({
providedIn: 'root'
})
export class SummonerService {
constructor( private http:HttpClient ) { }
summonerName
dataMatch
matchParticipants
matchHistory = [];
getSummoner(summonerName,regionId){
this.summonerName = summonerName
return this.http.get(`http://localhost:3000/summName/${summonerName}/${regionId}` )
};
getMatches(gameId){
return this.http.get( `http://localhost:3000/match/${gameId}`
).pipe(
tap( (data:any) => {
console.log(data.match);
this.dataMatch = data.match
this.matchParticipants = data.match.participants
}) ,
switchMap( data => {
return this.http.get(`http://ddragon.leagueoflegends.com/cdn/10.5.1/data/en_US/summoner.json`)
}),
tap( (data:any) =>{
let spellsObj = data.data;
const spellsArray:Array<any>[] = [];
Object.keys(spellsObj).forEach( key =>{
let spell = spellsObj[key]
spellsArray.push(spell)
});
this.matchParticipants.forEach( participants => {
let spellId1:any = spellsArray.find( (spell:any) => spell.key === JSON.stringify(participants.spell1Id) );
let spellId2:any = spellsArray.find( (spell:any) => spell.key === JSON.stringify(participants.spell2Id) );
let spellId1Image = `http://ddragon.leagueoflegends.com/cdn/10.5.1/img/spell/${spellId1.id}.png`
let spellId2Image = `http://ddragon.leagueoflegends.com/cdn/10.5.1/img/spell/${spellId2.id}.png`
participants.spellId1Info = spellId1
participants.spellId2Info = spellId2
participants.spellId1Info.image = spellId1Image
participants.spellId2Info.image = spellId2Image
});
}),
map ( data =>{
return this.dataMatch
})
)};
我放了部分代码,但我需要进行更多这样的调用。
switchMap( data => {
return this.http.get(`http://x.json`)
}),
我不知道这里的“switchmap”调用是否正确
Component.ts
onSubmit( ){
this.summ.getSummoner( this.summoner.name,this.summoner.regionId )
.pipe(
tap( (summoner:any) => this.matchHistory = summoner.matchHistory ),
concatMap( (summoner:any) => {
const observables = this.matchHistory
.map( element => this.summ.getMatches(element.gameId));
return forkJoin(observables)
}),
map( (matchesArray:any) => {
let gameIdArray = this.matchHistory.map( element => element.gameId)
this.matchesArray = matchesArray.sort((a, b) => {
return gameIdArray.indexOf(a.gameId) - gameIdArray.indexOf(b.gameId);
});
return matchesArray
})
) .subscribe();
【问题讨论】:
-
你能做一个简单的堆栈闪电战来展示你的问题,我们可以看看吗?
标签: javascript angular typescript rxjs angular8