【发布时间】:2021-03-16 15:21:50
【问题描述】:
我对 Angular 和一般编程很陌生。
我想使用setInterval 方法更改我的主页的背景图片。它应该每秒都在变化,但由于某种原因,它变化得更快。
组件:
export class AppComponent implements OnInit {
images: Image[] = [];
changeBackgroundCounter = 0;
constructor(private imagesService: ImagesService) {}
getImage() {
setInterval(() => {
this.changeBackgroundCounter = this.changeBackgroundCounter + 1;
if (this.changeBackgroundCounter > this.images.length - 1) {
this.changeBackgroundCounter = 0;
}
}, 1000);
return this.images[this.changeBackgroundCounter].image;
}
ngOnInit() {
this.images = this.imagesService.getImages();
console.log(this.images[0]);
}
}
模板:
<div [ngStyle]="{'background-image': 'url('+ getImage() + ')'}" [ngClass]="{imageBackground: getImage()}">
【问题讨论】:
-
getImage 被调用了很多次,所以你正在创建大量的间隔
标签: html angular typescript setinterval