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

如何在Angular中展示嵌套数组API数据并实现跳转详情页功能

问题核心原因

  • 你对SWAPI接口返回结构的使用逻辑错误,列表接口返回外层带results数组,单条角色接口直接返回角色对象不带外层包装
  • SWAPI单条角色查询用数字ID而非角色名作为查询参数,你当前传name的请求会404
  • 列表遍历逻辑、路由参数匹配也存在对应错误

分步修改代码

1. 先调整路由配置(app-routing.module.ts)

先确保路由参数名和组件里取值一致,示例配置:

const routes: Routes = [
  { path: 'actors', component: ActorListComponent },
  // 注意参数名是actorid,后面组件取值要对应
  { path: 'actors/:actorid', component: ActorSingleComponent },
  { path: '', redirectTo: '/actors', pathMatch: 'full' }
]

别忘了在AppModule里导入HttpClientModule,否则Http请求无法正常工作。

2. 修改actor.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  // 建议加providedIn: 'root' 不需要再在模块里声明provider
  providedIn: 'root'
})
export class ActorService {
  apiUrl = 'https://swapi.dev/api/people/'

  constructor(private http: HttpClient) { }

  getActors(){
    return this.http.get(`${this.apiUrl}`);
  }

  // 参数改为角色id,不需要加per_page参数
  getActor(actorId: string){
    return this.http.get(`${this.apiUrl}${actorId}/`);
  }
}

3. 修改actor-list.component.ts

import { Component, OnInit } from '@angular/core';
import { ActorService } from 'src/app/core/services/actor.service';

@Component({
  selector: 'app-actor-list',
  template: `
    <section class="section">
      <div class="container">
        <div class="columns is-multiline" *ngIf="actors | async as res">
          <!-- 遍历返回结果里的results数组 -->
          <div class="column is-4" *ngFor="let actor of res.results">
            <div class="card">
              <div class="card-content">
                <!-- 从角色的url属性里提取id,SWAPI返回的url格式是https://swapi.dev/api/people/1/,按/拆分取倒数第二个就是id -->
                <a [routerLink]="['/actors', actor.url.split('/').slice(-2)[0]]">
                  {{ actor.name }}
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  `,
  styles: []
})
export class ActorListComponent implements OnInit {
  actors;

  constructor(private actorService: ActorService) { }

  ngOnInit() {
    this.actors = this.actorService.getActors()
  }
}

4. 修改actor-single.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ActorService } from 'src/app/core/services/actor.service';

@Component({
  selector: 'app-actor-single',
  template: `
    <section class="section">
      <div class="container" *ngIf="actor">
        <div class="card">
          <div class="card-content">
            <h2>{{ actor.name }}</h2>
            <ul>
              <li>身高:{{ actor.height }}cm</li>
              <li>体重:{{ actor.mass }}kg</li>
              <li>发色:{{ actor.hair_color }}</li>
              <li>肤色:{{ actor.skin_color }}</li>
              <li>瞳色:{{ actor.eye_color }}</li>
              <li>出生年份:{{ actor.birth_year }}</li>
              <li>性别:{{ actor.gender }}</li>
            </ul>
          </div>
        </div>
      </div>
    </section>
  `,
  styles: []
})
export class ActorSingleComponent implements OnInit {
  actor: any;
  constructor( private actorService: ActorService, private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      // 取路由里的actorid参数
      const actorId = params['actorid'];
      this.actorService.getActor(actorId).subscribe(actor => this.actor = actor)
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:15:04