【问题标题】:Angular change img src on timeout超时时角度更改 img src
【发布时间】: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


【解决方案1】:

如果您需要访问this,请使用箭头功能或bind this 到该功能

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

同样在您的example 中,您需要先在构造函数中获取服务实例,然后再使用它,如果您的编辑器没有自动执行该操作,也需要将其导入。

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.
    }
}

【讨论】:

  • 构造函数中确实设置了,只是这里没有写。您的解决方案有效并将图片设置为第二个值。它不显示第一个文件值,然后 3 秒后更改为第二个值。它立即显示第二个值。 :)
  • @IkePr 那是因为所有超时都同时运行,请检查答案中的编辑。
  • 这行得通!您能否通过使用 i 递增值来详细说明这是如何工作的?
  • 对于第一种情况,i+1 的值为 1,因此 3000*1= 3000 或 3 秒,第二种情况为 2*3s,第三种情况类似,为 3*3s,依此类推。 .
  • 非常感谢@Shubanker,我标记为正确答案。现在我对这个解决方案有一个不同的问题。当我将计时器(3000)设置为自定义变量时,时间变得很混乱。示例:4000*(i),则 i 为 0。第二次迭代,3000*(i),则 3s OK。第三次迭代 4000*(i) 然后是 2...你知道发生了什么吗?或者我应该打开一个新线程吗?
猜你喜欢
  • 1970-01-01
  • 2012-09-28
  • 2016-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2013-05-23
相关资源
最近更新 更多