You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15中如何访问含多参数的API链接?

解决方案:Angular中正确获取指定赛事下的阶段资源

1. 确认路由参数配置

首先你的路由需要包含两个参数:赛事ID(champId)和阶段ID(stageId),示例路由配置如下:

// app-routing.module.ts
const routes: Routes = [
  // 其他路由...
  { path: 'championship/:champId/stage/:stageId', component: StatusPhaseComponent }
];

访问类似/championship/10/stage/168的路径时,路由参数就能正确获取到champId=10和stageId=168。

2. 修正Service中的方法

优化URL拼接逻辑,同时复用HTTP请求选项避免重复创建:

// urls.ts
const BASE_URL = "https://api.api-soccer.com/v1/";
export const CHAMPIONSHIP_URL = `${BASE_URL}championship`;

// services.ts
// 抽离HTTP选项为私有属性复用
private httpOptions = {
  headers: new HttpHeaders().set("Authorization", "Bearer test_potatobearer123")
};

getChampionshipById(champId: string) {
  return this.http.get(`${CHAMPIONSHIP_URL}/${champId}`, this.httpOptions);
}

// 明确参数顺序,确保URL拼接正确
getStageById(stageId: string, champId: string) {
  return this.http.get(`${CHAMPIONSHIP_URL}/${champId}/stages/${stageId}`, this.httpOptions);
}

3. 组件中正确获取路由参数并调用Service

之前的错误是传入了同一个路由参数,导致URL拼接错误。现在需要从路由中获取两个不同的参数并传入Service:

// camp.component.ts
export class StatusPhaseComponent {
  championship: any;
  stage: any;
  stagePhase: any;
 
  constructor(
    private activatedRoute: ActivatedRoute,
    private championshipsService: ChampionshipsService,
    private router: Router
  ) {
    this.activatedRoute.paramMap.subscribe((paramMap) => {
      const champId = paramMap.get('champId');
      const stageId = paramMap.get('stageId');
      
      if (champId && stageId) {
        // 获取指定赛事下的阶段数据
        this.championshipsService.getStageById(stageId, champId).subscribe((stageData) => {
          this.stage = stageData;
          console.log(stageData);
          // 这里可以将数据绑定到页面模板进行渲染
        });

        // 若需要同时获取赛事信息
        this.championshipsService.getChampionshipById(champId).subscribe((champData) => {
          this.championship = champData;
          this.stagePhase = champData.current_phase?.slug;
        });
      }
    });
  }
}

4. 优化:避免嵌套订阅(可选)

使用RxJS的forkJoin和switchMap组合请求,让代码更简洁:

// camp.component.ts
import { switchMap, forkJoin, EMPTY } from 'rxjs';

// ... 其他代码
this.activatedRoute.paramMap.pipe(
  switchMap((paramMap) => {
    const champId = paramMap.get('champId');
    const stageId = paramMap.get('stageId');
    if (!champId || !stageId) {
      return EMPTY;
    }
    return forkJoin([
      this.championshipsService.getChampionshipById(champId),
      this.championshipsService.getStageById(stageId, champId)
    ]);
  })
).subscribe(([champData, stageData]) => {
  this.championship = champData;
  this.stage = stageData;
  this.stagePhase = champData.current_phase?.slug;
});

内容的提问来源于stack exchange,提问作者Amanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:45:30