Angular中返回值集合后变量n未更新,仅显示n=0的postedpics求助
问题分析
你的代码存在三个核心问题:
getPosts函数提前返回:函数内部的for循环在第一次迭代时就执行了return postUrls,导致只收集了第一个post的图片,后续post的遍历完全没执行,n也只自增一次就停止。- 单次赋值无法更新:
ngOnInit只调用一次getPosts,galleryPosts只会被赋值一次,永远是第一个post的图片集合。 - 所有画廊绑定同一数据源:HTML中每个
post对应的ngx-gallery都绑定了同一个galleryPosts变量,导致所有画廊显示的都是第一组图片。
解决方案
方案一:HTML中直接转换图片格式(最简洁)
不需要额外的TS逻辑,直接在HTML中把当前post的postedpics转换成ngx-gallery需要的格式:
修改后的component.html
<div *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>
修改后的component.ts
删除无用的n变量、getPosts函数以及ngOnInit中的赋值:
... ngOnInit(): void { // 此处无需额外代码 } // 删掉n变量和getPosts函数 ...
方案二:TS中预处理图片集合(更清晰)
如果不想在HTML中写逻辑,可以在TS中提前为每个post生成对应的画廊图片数组:
修改后的component.ts
import { NgxGalleryImage } from 'ngx-gallery'; ... postGalleryImages: NgxGalleryImage[][] = []; ngOnInit(): void { // 遍历所有post,为每个post生成对应的画廊图片数组 this.postGalleryImages = this.member.posts.map(post => post.postedpics.map(pic => ({ small: pic?.url, medium: pic?.url, big: pic?.url })) ); } ...
修改后的component.html
通过循环索引绑定对应位置的图片集合:
<div *ngFor="let m of member.posts; let i = index"> <p>{{m.description}}</p> <p *ngFor="let s of m.postedpics">{{s.url}}</p> <ngx-gallery class="mt-4" [options]="galleryOptions" [images]="postGalleryImages[i]" style="display: inline-block; margin-bottom: 20px;"></ngx-gallery> </div>
内容的提问来源于stack exchange,提问作者Peter Parker
相关产品推荐
相关产品推荐

