如何在前端正确显示图片的多个版本.角度



从后端进入网络的同一图像有几个不同大小。这是最近为优化目的而做的。以前,用户可以上传太大的图片,而且在某些页面上非常繁忙。

如果图片是在实现此图像压缩功能之前上传的,则网络会接收到一个空数组。如果在之后,那么这个图片中有三个不同大小的对象。

这可能是一个非常天真和愚蠢的问题,但我如何默认输出压缩图像?如果";尺寸":[]将是一个空数组,然后离开旧的映像路径?

我尝试过这个选项,但不起作用:<img[src]=";placegallery[0].file.sizes[0].tumb|placegallery[0].file.tumb"gt;

// This comes from the backend:
{
"id": 1016,
"file_id": 1653,
"place_id": 55,
"order": 2,
"cover": 0,
"file": {
"id": 1653,
"type": "image",
"path": "https://<<CORRENT URL>>",
"thumb": "https://<<CORRENT URL>>",
"created_at": "2022-03-15 16:58:50",
"updated_at": "2022-03-15 16:58:50",
"sizes": [
{
"id": 10,
"file_id": 1653,
"size": "small",
"path": "https://<<CORRENT URL>>"
},
{
"id": 11,
"file_id": 1653,
"size": "medium",
"path": "https://<<CORRENT URL>>"
},
{
"id": 12,
"file_id": 1653,
"size": "big",
"path": "https://<<CORRENT URL>>"
}
]
}
},
{
"id": 1017,
"file_id": 551,
"place_id": 55,
"order": 3,
"cover": 0,
"file": {
"id": 551,
"type": "image",
"path": "https://<<CORRENT URL>>",
"thumb": "https://<<CORRENT URL>>",
"created_at": "2021-12-28 02:37:56",
"updated_at": "2021-12-28 02:37:56",
"sizes": []
}
}

<div class="place-gallery" *ngIf="place.gallery.length">
<div (click)="appService.openLightbox(0, place.getAlbumGallery)" class="place-gallery-item">
<img [src]="place.gallery[0].file.thumb">
</div>
<div *ngIf="place.gallery.length >= 2"(click)="appService.openLightbox(0, place.getAlbumGallery)" class="place-gallery-all">
{{HelperService.translate('website.places.photos')}}
(<span>{{place.gallery.length}}</span>)
</div>
</div>
<div class="place-gallery-middle" *ngIf="place.gallery.length >= 2">
<div (click)="appService.openLightbox(1, place.getAlbumGallery)" class="place-gallery-item">
// It doesn't work
<img [src]="place.gallery[1].file.sizes[0].thumb || place.gallery[1].file.thumb">
</div>
<div (click)="appService.openLightbox(2, place.getAlbumGallery)" class="place-gallery-item" *ngIf="place.gallery.length >= 3">
<img [src]="place.gallery[2].file.thumb">
</div>
</div>

试试这个:

<img [src]="place.gallery[0].file.sizes.length ? place.gallery[0].file.sizes[0].thumb : place.gallery[0].file.thumb">

我们在这里所做的:

place.gallery[0].file.sizes.length ?首先检查大小数组是否有元素(当长度为0时,JavaScript理解为false语句。如果它大于0,我们会选择第一个项目,即"size": "small",对吗?

如果sizes阵列长度为0,则回退到place.gallery[0].file.thumb

帮助链接:

所有没有";值";是错误的

条件(三元(算子

怎么了

place.gallery[0].file.sizes[0].thumb || ...当你这样检查时,sizes[0]不存在,因为size是一个空数组,所以它返回undefined,你不能从undefined中读取.thumb

最新更新