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

Angular如何让详情组件加载与列表路径对应的相同图片

问题修复方案

你现有代码存在3个核心错误:

  1. 列表页路由跳转传递的是角色对应序号(i+1),但详情页错误尝试读取actorname参数,参数名和取值逻辑不匹配
  2. 详情页模板加了无意义的*ngFor="let i = index",没有可遍历的数组导致index变量不存在
  3. 详情页图片路径多写了多余的单引号,属于语法错误

具体修改步骤

1. 先确认路由配置

确保你的路由模块中,详情页的路由配置参数名和传参对应,示例如下:

// app-routing.module.ts 对应配置
const routes: Routes = [
  // 其他路由...
  { path: 'actors/:actorId', component: ActorSingleComponent }
]

2. 修改ActorSingleComponent组件代码

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">
        <div class="card" *ngIf="actor">
          <section class="hero is-info">
            <div class="hero-body">
              <h1 class="title is-1 ml-4 mb-6">{{ actor.name }}</h1>
            </div>
          </section>

          <div class="message-body">
              <figure class="image is-4by3 mt-6">
                <img src="./assets/img/{{ imgId }}.jpg"  alt="{{actor.name}}">
              </figure>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Height : {{ actor.height }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Mass : {{ actor.mass }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Hair Color : {{ actor.hair_color }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Skin Color : {{ actor.skin_color }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Eye Color : {{ actor.eye_color }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Birth Year : {{ actor.birth_year }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Gender : {{ actor.gender }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Created : {{ actor.created }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Edited : {{ actor.edited }}</h2>
            <h2 class="subtitle is-4 ml-6 mb-1 pd-0">Url : {{ actor.url }}</h2>
          </div>
        </div>
      </div>
    </section>
  `,
  styles: [
  ]
})
export class ActorSingleComponent implements OnInit {
  actor;
  imgId: number; // 新增变量存储图片序号
  constructor( private actorService: ActorService, private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.params.subscribe(async params => {
      // 读取路由传递的序号
      this.imgId = Number(params['actorId']);
      // 若原有getActor方法需要传name,可先获取全量actor列表后通过imgId-1作为索引取对应数据
      this.actor = await this.actorService.getActor(this.imgId);
      console.log(this.actor)
    });
  }
}

3. 列表页路由适配(可选)

如果你的路由前缀和示例不一致,需要把列表页的routerLink修改为对应路径:

<a [routerLink]="['/actors', i+1]" >{{ actor.name }}</a>

内容的提问来源于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.03 03:48:03