timer.unsubscribe 不是函数 Angular2

timer.unsubscribe is not a function Angular2

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

应该是:

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

一个更清楚和简单的例子是这个 试试这个例子,我觉得更清楚。

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


}