如何使用json连接angular中的图像



我有下面的结构,其中我有json格式的图像数据,该格式有到assets文件夹的链接。所有图像的放置位置。我正在考虑使用这种使用图像进行测试的方式,因为将来我们将在网络中的某个地方拥有图像,并将基于类似的JSON:从那里获取图像

- app
- core
- data 
- img.json
- layout
- test.component.ts
- assets
- images

img.json

{
"items" : [
{
"img": "/assets/images/test1.png",
"alt" : "Image 1"
},
{
"img": "/assets/images/test2.png",
"alt" : "Image 2"
},
{
"img": "/assets/images/test3.png",
"alt" : "Image 3"
}
]
}

测试组件.ts

import images from '../../data/img.json';
export class SlideshowComponent implements OnInit {
showNavigationArrows = false;
showNavigationIndicators = false;
items = [0, 1, 2].map((n) => images);
constructor(config: NgbCarouselConfig) {
// customize default values of carousels used by this component tree
config.showNavigationArrows = true;
config.showNavigationIndicators = true;
}    
}

HTML

<ngb-carousel *ngIf="items" [showNavigationArrows]="showNavigationArrows" 
[showNavigationIndicators]="showNavigationIndicators">
<ng-template ngbSlide *ngFor="let item of items">
<div class="picsum-img-wrapper">
<img [src]="item" alt="Random slide">
</div>
</ng-template>
</ngb-carousel>

我无法将图像连接到HTML,任何帮助都将非常好。

假设您的tsconfig被正确配置为导入json(如果没有,您的ts编译器会向您抛出错误(

你应该能够做到这一点:

items = images.items; // not sure why you had that index -> map structure?

<ng-template ngbSlide *ngFor="let item of items">
<div class="picsum-img-wrapper">
<img [src]="item.img" alt="{{ item.alt }}"> <!-- access the url and use the alt text -->
</div>
</ng-template>

额外基于评论:

如果你想选择性地显示一个视频标签,我建议你这样做:

items = images.items.map(i => Object.assign({}, i, {isVideo: i.img.endsWith('.mov')})) // this only works for mov obviously

模板:

<ng-template ngbSlide *ngFor="let item of items">
<div class="picsum-img-wrapper">
<img *ngIf="!item.isVideo" [src]="item.img" alt="{{ item.alt }}"> <!-- simple ngIf to show right tag -->
<video *ngIf="item.isVideo" [src]="item.img" alt="{{ item.alt }}" controls></video>
</div> 
</ng-template>

最新更新