繁体   English   中英

如何使用 Angular 在同一个函数中进行多个 http 调用

[英]How to make multiple http calls in the same function with Angular

我想要实现的目标:从 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();

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 响应数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM