我正在开发一个项目,我在其中添加了一个轮播,但是当我应用
this.autoPlay()
时,页面会在浏览器上呈现,但只是不断加载,并且页面上没有任何可见内容,但是当我删除this.autoPlay()
时页面工作正常,但我非常需要它但它无法工作,我该如何解决这个问题。
检查我的代码并给我解决方案
import { Component } from '@angular/core';
import { homeCarouselData } from '../../../Data/mainCarousel';
@Component({
selector: 'app-main-carousel',
templateUrl: './main-carousel.component.html',
styleUrls: ['./main-carousel.component.scss']
})
export class MainCarouselComponent {
carouselData:any;
currentSlide=0;
interval:any;
ngOnInit() {
this.carouselData=homeCarouselData;
this.autoPlay();
}
autoPlay(){
setInterval(()=>{
this.nextSlide();
},2000)
}
nextSlide() {
this.currentSlide=(this.currentSlide+1) % this.carouselData.length;
}
}
您的
autoPlay()
函数的问题似乎是您在使用 setInterval()
时没有正确管理它,
这可能会导致性能问题或无限循环,从而导致页面不断加载。
所以你需要做的是当组件被销毁时取消
setInterval
。
您还必须将 OnDestroy
添加到组件的标题中才能实现它,它看起来像这样:
export class MainCarouselComponent implements OnInit, OnDestroy{}
并添加以下功能:
ngOnDestroy() {
// Clearing the interval when the component is destroyed
if (this.interval) {
clearInterval(this.interval);
}
}