角度误差this.mymethod不是一个函数 [英] Angular error this.mymethod is not a function

查看:54
本文介绍了角度误差this.mymethod不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 5组件中创建一个图像滑块。滑块有上一个和下一个控件,它们都可以正常工作,但我无法自动滑动。

I'm trying to create an image slider inside my Angular 5 component. The slider has Previous and Next controls which both work fine but I can't get it to slide automatically.

<!-- 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作为参数。这两个按钮都工作正常。但是,我还希望滑块自动滑动,因此自动滑动方法,但在调用它时,它会输出错误消息TypeError:this.imageCycle不是函数。
我做错了什么?我真的很感激一些帮助。

My Next and Previous buttons both call the imageCycle() method passing in 1 for next and -1 for previous as the parameters. Both these buttons work fine. However, I would also like for the slider to slide automatically hence the autoslide method but upon calling it, it errors out with the message "TypeError: this.imageCycle is not a function". What am I doing wrong? I'd really appreciate some help.

推荐答案

更改

setTimeout(this.autoslide, 2000)

to

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

以指向当前的类实例。

for this to keep pointing to the current class instance.

这篇关于角度误差this.mymethod不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆