一个更清晰和简单的例子是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();
}
}