timer.unsubscribe不是Angular2函数

时间:2016-10-21 16:10:11

标签: angular timer angular2-observables

尝试制作一个简单的计时器,需要在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();
        });

2 个答案:

答案 0 :(得分:11)

应该是:

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

您不能unsubscribe Observable,只能Subscription

Plunker example

答案 1 :(得分: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();
  }


}