4

试图制作一个简单的计时器,并且需要在某些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();
        });
4

2 回答 2

14

它应该是:

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 示例

于 2016-10-21T16:14:12.420 回答
2

一个更清晰和简单的例子是this try this example,我认为更清楚。

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


}
于 2017-07-28T06:51:42.567 回答