timer.unsubscribe не является функцией Angular2

Пытался сделать простой таймер и нужно сломать его по какому-то if условию. Но всегда выдавал ошибку EXCEPTION: timer.unsubscribe is not a function.

Что я делаю не так?

    let timer:any = Observable.timer(0,1000);
    timer.subscribe(data => {
            console.log(this.itemsRatedList);
            if(data == 5) timer.unsubscribe();
        });

person s.spirit    schedule 21.10.2016    source источник


Ответы (2)


Так должно быть:

let timer:any = Observable.timer(0,1000);
let subscription = timer.subscribe(data => {
  console.log(this.itemsRatedList);
  if(data == 5) 
    subscription.unsubscribe();
});

Вы не можете unsubscribe и Observable, только Subscription.

Пример планкера

person Günter Zöchbauer    schedule 21.10.2016
comment
Вау... Так невнимательно с моей стороны :) Спасибо! - person s.spirit; 21.10.2016

Более наглядный и простой пример - вот этот пример, я думаю, более понятный.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.css']
})


export class SliderComponent implements OnInit , AfterViewInit, OnDestroy {

  Sliders: any;
  timer: any;
  subscription: any;


 constructor() { }

 ngOnInit() {

   // after 3000 milliseconds the slider starts
   // and every 4000 miliseconds the slider is gona loops

   this.timer = Observable.timer(3000, 4000);

   function showSlides() {
     console.log('Test');
   }

   // This is the trick
   this.subscription = this.timer.subscribe(showSlides);

 }

  // After the user live the page
  ngOnDestroy() {
    console.log('timer destroyd');
    this.subscription.unsubscribe();
  }


}
person Community    schedule 28.07.2017