gpt4 book ai didi

javascript - Angular 错误this.mymethod is not a function

转载 作者:行者123 更新时间:2023-11-30 09:26:03 26 4
gpt4 key购买 nike

我正在尝试在我的 Angular 5 组件中创建一个图像 slider 。 slider 具有 Previous 和 Next 控件,它们都可以正常工作,但我无法让它自动滑动。

<!-- language: lang-typescript -->
import { Component, OnInit, ElementRef, Renderer2 } from '@angular/core';
@Component({...})
export class HomeComponent implements OnInit {

private slides;
private dots;
private slideIndex: any = 1
private len;

constructor(private el: ElementRef, private renderer: Renderer2) {
}

ngOnInit() {
/* Gets a nodelist of the slider images in the DOM */
this.slides = this.el.nativeElement.querySelectorAll(".slide");
/* The control dots at the bottom of the slider */
this.dots = this.el.nativeElement.querySelectorAll(".slider__dots > *")
this.len = this.slides.length

this.showImage(this.slideIndex)
this.autoslide() /* Errors out with the message "this.imageCycle is not a function" */
}

/* The main slider method */
showImage(n) {

if (n > this.len) { this.slideIndex = 1 }
if (n < 1) { this.slideIndex = this.len }

for (let i = 0; i < this.len; i++) {
this.renderer.setStyle(this.slides[i], 'display', 'none')
this.renderer.removeClass(this.dots[i], 'active-dot')
}

this.renderer.addClass(this.slides[this.slideIndex-1], 'fade')
this.renderer.setStyle(this.slides[this.slideIndex-1], 'display', 'block')
this.renderer.addClass(this.dots[this.slideIndex-1], "active-dot")
}


/* Cycles through the images, either previous or next */
imageCycle(n) {
this.showImage(this.slideIndex += n)
}

/* Handles the dots */
currentImage(n) {
this.showImage(this.slideIndex = n)
}

/* Automatically slide through the images */
autoslide() {
this.imageCycle(1)
setTimeout(this.autoslide, 2000)
}
}

我的 Next 和 Previous 按钮都调用 imageCycle() 方法,传入 1 代表 next 和 -1 代表 previous 作为参数。这两个按钮都可以正常工作。但是,我也希望 slider 自动滑动,因此使用 autoslide 方法,但在调用它时,它会出错并显示消息“TypeError: this.imageCycle is not a function”。我究竟做错了什么?非常感谢您的帮助。

最佳答案

改变

setTimeout(this.autoslide, 2000)

setTimeout(this.autoslide.bind(this), 2000)

this一直指向当前的类实例。

关于javascript - Angular 错误this.mymethod is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com