【问题标题】:Angular2 Variable 'Undefined' Outside MethodAngular2变量“未定义”外部方法
【发布时间】:2016-06-25 04:41:40
【问题描述】:

我在一个方法中订阅了一个 observable,并且需要在另一个方法中取消订阅它。 subCounter() 方法是从一个 init 函数调用的,内容工作正常。

subCounter() {
  this.fml = this.playerService.counter(this.song).subscribe(data => {
    this.pos = data;
    this.time.position = Math.round(this.pos);
    this.time.dur = this.song.duration - this.time.position;
    this.time.durMinutes = Math.floor(this.time.dur / 60);
    this.time.durSeconds = ('0' + Math.ceil(this.time.dur - this.time.durMinutes * 60)).slice(-2);
    this.time.posMinutes = Math.floor(this.time.position / 60);
    this.time.posSeconds = ('0' + Math.ceil(this.time.position - this.time.posMinutes * 60)).slice(-2);
    this.time.percent = this.time.position / this.song.duration * 100;
  })
  // This works just fine
  console.log(this.fml);
}

当我调用 touchActivate() 函数时,它包含一个取消订阅该变量的函数,但它会抛出一个错误,因为 this.fml.unsubscribe 未定义。控制台日志记录 this.fml 在未定义的对象中返回。

touchActivate() {
  console.log(this.fml);
  this.fml.unsubscribe();
}

在我的班级顶部,我定义了变量: public fml: any;

【问题讨论】:

  • 如何调用touchActivate方法?
  • @yurzui 带有touchstart 事件的事件侦听器。
  • 你能给我们看看touchstart事件监听器的代码吗?
  • @yurzui $('.range-slider').on("touchstart", this.touchActivate);

标签: javascript typescript angular observable


【解决方案1】:

试试这个:

$('.range-slider').on("touchstart", this.touchActivate.bind(this));

或者使用箭头函数保留this

$('.range-slider').on("touchstart", () => this.touchActivate());

【讨论】:

  • 箭头功能非常适合我。谢谢!
猜你喜欢
  • 2018-05-14
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多