timer.unsubscribe is not a function Angular2

后端 未结 2 1523
无人及你
无人及你 2021-01-13 14:42

Tried to make a simple timer and need to break it on some if condition. But always got an error EXCEPTION: timer.unsubscribe is not a function.

相关标签:
2条回答
  • 2021-01-13 15:14

    It should be:

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

    You can't unsubscribe an Observable, only a Subscription.

    Plunker example

    0 讨论(0)
  • 2021-01-13 15:32

    A more clear and simple example is this try this example, I think is more clear.

    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();
      }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题