繁体   English   中英

超时时角度更改 img src

[英]Angular change img src on timeout

在我的 html 中,我有:

<img src="{{activeImage}}" class="img-fluid img-file img-center-style">

在 .ts 中, activeImage定义了一个默认值:

  promotions: any = [];
  activeImage: string = 'assets/Promo_1.jpg';

现在在ngOnInit方法中,我调用了一个服务,该服务返回以下内容并将其设置在促销中 在此处输入图片说明

我的目标是什么

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)。

现在,如果我在没有任何 setTimeout 或任何东西的情况下在ngOnInit 中设置它,它可以正常工作并且可以很好地设置图片:

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。

如果需要访问this使用箭头函数或this 绑定到函数

setTimeout(()=> {
    //SET SRC TO FILE FROM PROMOTIONS
    this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
}, 3000);

同样在您的示例中,您需要在使用之前在构造函数中获取服务实例,如果您的编辑器没有自动执行此操作,也需要导入它。

constructor(private mainService : mainService){}

编辑:

要每 3 秒更改一次图像,请使用增量值设置计时器:

setActiveImage(promotions) {
    for (let i = 0; i <= promotions.length - 1; i++) {
      console.log("one promotion is: ", promotions[i]);
      setTimeout( ()=> {
      //SET SRC TO FILE FROM PROMOTIONS
        this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
      }, 3000*(i+1)); //Change i+1 to i if you don't want delay for 1st image.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM