2016-10-21 10 views
1

Пробовал делать простой таймер и должен разорвать его на некотором if состоянии. Но всегда получалось сообщение об ошибке EXCEPTION: timer.unsubscribe is not a function.timer.unsubscribe не является функцией Angular2

Что я делаю неправильно?

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

ответ

5

Оно должно быть:

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

Вы не можете unsubscribeObservable, только Subscription.

Plunker example

+0

Вау ... Так невзирая на меня :) Спасибо! –

1

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

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


}