Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
template: `
<div>{{ count }}</div>
<button (click)="startCounting()">Start Counting</button>
`
})
export class CounterComponent implements OnInit, OnDestroy {
count: number;
private _destroyed$ = new Subject();
ngOnInit() {
this.startCounting();
}
ngOnDestroy() {
this._destroyed$.next();
this._destroyed$.complete();
}
startCounting() {
interval(1000)
.pipe(takeUntil(this._destroyed$))
.subscribe(count => this.count = count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.