timer.unsubscribe is not a function Angular2

2020-03-25 03:40发布

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.

What am I doing wrong?

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

2条回答
Rolldiameter
2楼-- · 2020-03-25 04:03

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

查看更多
Bombasti
3楼-- · 2020-03-25 04:29

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


}
查看更多
登录 后发表回答