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

Angular 12使用NgxGallery报错TypeError: this.c[i] is undefined求助

Angular 12中NgxGallery报错this.c[i] is undefined及图片不显示问题解决

错误根源解析

  1. 变量赋值与访问不匹配:你在getPosts方法中把this.c赋值为单个post对象(this.c = this.member.posts[i]),却错误地用数组下标this.c[i]去访问它,直接导致undefined错误。
  2. 图片数组访问错误:内部循环中用this.c[j]获取图片是错误的,实际应该从当前post的postedpics数组中取值。
  3. 提前返回截断逻辑:第一个for循环内的return postUrls会直接终止方法,只会收集第一个post的图片,后续post的图片无法被处理。

修正后的组件代码(member.component.ts)

如果需要展示所有post的图片到同一个画廊,可修改getPosts方法如下:

ngOnInit(): void {
  this.galleryPosts = this.getPosts();
  // ...其他初始化代码
}

// 移除不必要的n、c变量,简化逻辑
getPosts(): NgxGalleryImage[] {
  const postUrls: NgxGalleryImage[] = [];
  // 遍历所有post
  for (const post of this.member.posts) {
    // 遍历当前post下的所有图片
    for (const pic of post.postedpics) {
      postUrls.push({
        small: pic.url,
        medium: pic.url,
        big: pic.url
      });
    }
  }
  return postUrls;
}

分post展示独立画廊的HTML写法(member.component.html)

如果需要每个post单独展示自己的图片画廊,无需在组件中额外处理,直接在模板中用map转换图片格式即可:

<div *ngIf="member?.posts" *ngFor="let m of member.posts">
  <p>{{m.description}}</p>
  <p *ngFor="let s of m.postedpics">{{s.url}}</p>
  <ngx-gallery class="mt-4" 
               [options]="galleryOptions" 
               [images]="m.postedpics.map(pic => ({small: pic.url, medium: pic.url, big: pic.url}))"
               style="display: inline-block; margin-bottom: 20px;">
  </ngx-gallery>
</div>

关于你尝试的第二种写法的问题

你之前写的[images]="small:s.url;medium:s.url;big:s.url"是错误的,因为[images]需要接收一个符合NgxGalleryImage格式的数组,而非键值对字符串。上述模板中的map方法是正确的转换方式。

额外防坑提示

确保member.posts和postedpics已正确加载(比如API请求完成后再渲染),可以通过*ngIf="member?.posts"避免初始空值导致的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:20:34