Drakee510
Drakee510

Reputation: 500

Angular2 Variable 'Undefined' Outside Method

I am subscribing to an observable within a method and need to unsubscribe from it within another. The subCounter() method is called from an init function and the contents work just fine.

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);
}

When I call my touchActivate() function, it contains an unsubscribe function to that variable stored, however it throws an error as this.fml.unsubscribe is undefined. Console logging this.fml returns in an undefined object.

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

At the top of my class I have the variable defined: public fml: any;

Upvotes: 0

Views: 307

Answers (1)

yurzui
yurzui

Reputation: 214007

Try this:

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

Or use arrow function to retain this:

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

Upvotes: 1

Related Questions