Ionic应用中等待AWS S3图片加载时保留骨架屏方案咨询
解决方案:图片加载时保留骨架屏
步骤1:修改组件代码,跟踪图片加载状态
在获取房产数据后,给每个房产添加pictureLoading数组,标记对应图片的加载状态,初始值全为true:
async getProperties(proptype: any, operation: any) { this.propertiesService.getPropertiesPagination(proptype, operation).subscribe((res: any) => { this.properties = res.properties.map(property => { // 初始化图片加载状态数组,默认所有图片未加载完成 property.pictureLoading = property.pictures.map(() => true); const picuresEncoded = []; property.pictures.forEach(picture => { const encodedPictureKey = encodeURIComponent(picture.Key); const src = `http://localhost:3000/properties/getImage/${encodedPictureKey}`; picuresEncoded.push(src); }); property.pictures = picuresEncoded; return property; }); this.page++; this.isLoading = false; }); }
步骤2:修改HTML模板,切换骨架屏与图片显示
先修正原模板中this.property的错误(改为property),然后添加骨架屏元素,通过图片的load事件更新加载状态,控制显示切换:
<div class="card" *ngFor="let property of properties" (click)="viewProperty(property._id, property.tipoPropiedad)" > <swiper-container [direction]="'horizontal'" no-padding id="slider"> <swiper-slide *ngFor="let picture of property.pictures; let i = index"> <!-- 图片加载骨架屏 --> <div class="image-skeleton" *ngIf="property.pictureLoading[i]"></div> <!-- 实际图片,加载完成后隐藏骨架屏 --> <img [src]="picture" alt="Foto" class="thumbnail" (load)="property.pictureLoading[i] = false" [hidden]="property.pictureLoading[i]" /> </swiper-slide> </swiper-container> <div class="details"> <p class="title">{{property.titulo}}</p> <span class="location" *ngIf="property.ocultarUbicacion !== 'true'"> {{property.ubicacion.calle}}, {{property.ubicacion.localidad}} </span> <p class="price" *ngIf="property.operacion === 'alquiler'"> {{property.precioFormateado}} Mes </p> <p class="price" *ngIf="property.operacion === 'venta'"> {{property.precioFormateado}} </p> </div> </div>
步骤3:添加骨架屏样式
在对应CSS/SCSS文件中添加骨架屏样式,模拟图片占位效果:
.image-skeleton { width: 100%; height: 200px; /* 根据你的卡片图片高度调整 */ background-color: #f0f0f0; border-radius: 8px; animation: skeleton-loading 1.5s linear infinite alternate; } @keyframes skeleton-loading { 0% { background-color: #f0f0f0; } 100% { background-color: #e0e0e0; } } .thumbnail { width: 100%; height: 200px; /* 和骨架屏高度保持一致 */ object-fit: cover; border-radius: 8px; }
关键说明
- 每张图片对应独立的加载状态,单张图片加载完成后才替换骨架屏,不影响其他图片
- 完全保留你原有的图片获取流程(通过Express代理获取S3图片),无需修改后端逻辑
- 骨架屏的颜色、动画时长等参数可根据UI需求调整
内容的提问来源于stack exchange,提问作者mariolototo
相关产品推荐
相关产品推荐

