2016-10-21 2 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(); 
}); 

할 수 있습니다하지 unsubscribeObservableSubscription.

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


} 
관련 문제