首页 > 解决方案 > 如何使用 Angular 在同一个函数中进行多个 http 调用

问题描述

我想要实现的目标: 从 component.ts 调用 this.getMatches 服务,在 this.getMatches 中我必须进行一些 API 调用并处理我得到的数据,然后才能将其推送到数组

我做了什么: 1:函数运行并将“gameId”作为参数发送给函数this.getmatches。我得到每个匹配的数组,其中包含我推送到每个匹配的所有数据 2:我能够找到一个经过多次尝试后有效的方法,但是当它返回数组时它失败了

问题: 有时它返回相同的匹配,我注意到当我添加“swtichmap”运算符时会发生这种情况。

返回

服务.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”的调用是否正确完成

组件.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();

标签: javascriptangulartypescriptrxjsangular8

解决方案


switchMap这里看起来不错,如果您对此不确定,请随时查看我关于此主题的博客文章:https ://dev.to/rxjs/about-switchmap-and-friends-2jmm 。

如果要发出多个请求,则需要在 中应用组合运算符switchMap,可能是mergeforkJoin。代码可能如下所示:

 switchMap( data => merge(
    this.http.get(`http://x.json`),
    this.http.get(`http://y.json`),
    this.http.get(`http://z.json`)
)),

所以问题是你想使用哪一个:

当您并不真正关心其他 HTTP 调用是否已经完成时,您想使用合并。每次这些 HTTP 请求中的一个返回响应时,您将在 switchMap 之后获得一个新值,并且您也只会得到那个响应。

当您关心所有 HTTP 调用在您开始之前完成时,您希望使用forkJoin 。您还将获得一个 HTTP 响应数组,可用于继续处理。


推荐阅读