【发布时间】:2020-01-26 14:06:56
【问题描述】:
在我的 html 中,我有:
<img src="{{activeImage}}" class="img-fluid img-file img-center-style">
在.ts中,activeImage定义了一个默认值:
promotions: any = [];
activeImage: string = 'assets/Promo_1.jpg';
现在在 ngOnInit 方法中,我调用一个服务,该服务返回以下内容并将其设置在 promotions 中:
我的目标是什么:
将 activeImage 更改为 Commercial_file 数组中 file 的值。 (它总是有一个元素 - 0)。然后在一段时间后,将值更改为数组中的第二个文件。
这是我尝试过的:
ngOnInit() {
this.mainService.getPromotion().subscribe(promotions => {
console.log("getPromotion from servise are ", promotions);
this.promotions = promotions;
//If there is something, call method setActiveImage and send array
if (this.promotions.length > 0) {
this.setActiveImage(this.promotions);
}
});
}
setActiveImage(promotions) {
for (let i = 0; i <= promotions.length - 1; i++) {
console.log("one promotion is: ", promotions[i]);
setTimeout(function () {
//SET SRC TO FILE FROM PROMOTIONS
this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
}, 3000);
}
}
img src应该有3s的文件值,然后更改为第二个图像值。但这不会发生,它只是显示开头定义的默认值(assets/Promo_1.jpg )。
现在,如果我在 ngOnInit 中设置它而没有任何 setTimeout 或任何东西,它可以正常工作并且可以很好地设置图片:
this.activeImage = 'http://myurl/public/Commercials/' + this.promotions[0].commercial_file[0].file;
StackBlitz:https://stackblitz.com/edit/angular-5fteig?file=src%2Fapp%2Fapp.component.ts
TLDR:使用从服务器收集的数据在 3 秒内更改 img src。
【问题讨论】:
-
首选这种语法
[src]="activeImage"
标签: javascript angular typescript