我想在angular2中构建滑块,但我遇到了很多麻烦。好吧,让我们回到主要问题。为什么这个函数会给我这个错误
“错误错误:未捕获(在承诺中):RangeError:超出最大调用堆栈大小 RangeError:最大调用堆栈大小超出“
这是我的代码(我已经尝试过ViewChild等很多东西,现在已经遇到了这个问题)。
import { Component, OnInit, AfterViewInit, Input, ViewChild }
from '@angular/core';
@Component({
selector: 'slider',
template: `
<div class="slider-container">
<header>
<div class="slider-information">
<span class="slider-information--title" id="slidername">Acer C720-2103 Chromebook</span>
<span class="slider-information--category">
Category: <span id="slidercategory">Laptops</span>
</span>
<span class="slider-information--learnmore">
More about <span id="sliderinfoname">Acer C720-2103 Chromebook</span>
</span>
</div>
<div class="slider-image">
<img id="sliderimage" src="../../../images/slider/laptop-slider.jpg" alt="Laptop">
</div>
</header>
</div>
`,
styles: [`
:host{
overflow: hidden;
}
`]
})
export class SliderComponent implements OnInit, AfterViewInit {
sliderCount: number = 0;
images: any[];
constructor() { }
ngOnInit() {
this.images = this.createImages();
}
ngAfterViewInit() {
this.slider();
}
slider(): void{
var slidername = document.getElementById('slidername');
var sliderimage = document.getElementById('sliderimage');
var sliderinfoname = document.getElementById('sliderinfoname');
var slidercategory = document.getElementById('slidercategory');
if(this.sliderCount > this.images.length - 1){
this.sliderCount = 0;
}
slidername.innerHTML = this.images[this.sliderCount].name;
sliderimage.setAttribute('src', this.images[this.sliderCount].url);
sliderinfoname.innerHTML = this.images[this.sliderCount].name;
slidercategory.innerHTML = this.images[this.sliderCount].category;
this.sliderCount += 1;
debugger;
setTimeout(this.slider(), 2000);
}
createImages(): any[]{
var newImages: any[];
newImages = [
{ url: "../../../images/slider/laptop-slider.jpg", category: "Laptop" , name: "Acer C720-2103 Chromebook" },
{ url: "../../../images/slider/mobilephone-slider.jpg", category: "Phone", name: "Samsung Edge S6" }
]
return newImages;
}
}
有什么问题?
更新
我改变了这一点
setTimeout(this.slider(), 2000);
到setTimeout(this.slider, 2000);
。它只适用于第一个iternation。在第二个我得到“错误类型错误:无法读取未定义的属性'长度'
答案 0 :(得分:1)
首先你打电话
来自this.slider()
内的 this.slider()
,因为您正在调用它而不是传递对this.slider
的引用,这导致堆栈溢出。
现在您传递的参考文件没有this
正确绑定。将其更改为
setTimeout(() => this.slider(), 2000);
在正确设置this.slider()
的情况下2秒后运行this
。见How to access the correct `this` context inside a callback?
如果你打电话给document.getElementById()
,你就不会像Angular那样做。您从DOM中挖掘出的数据应该传递给您的组件,而不是将组件紧密耦合到环境中。