I thought it made more sense to create the timer as a Service so I can have more flexibility when creating my views (use the returned Time model however you want in your components). It creates a new observable upon subscription so each subscriber gets their own observable. In short, you can create as many timers at the same time with this service as you want. Be sure to include this service in your AppModule provider's array so you can use it throughout your application.
Service:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/defer';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
export interface Time {
days: number;
hours: number;
minutes: number;
seconds: number;
}
@Injectable()
export class TimerService {
constructor() { }
private createTimeObject(date: Date): Time {
const now = new Date().getTime();
const distance = date.getTime() - now;
let time: Time = {days: 0, hours: 0, minutes: 0, seconds: 0};
time.days = Math.floor(distance / (1000 * 60 * 60 * 24));
time.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
time.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
time.seconds = Math.floor((distance % (1000 * 60)) / 1000);
return time;
}
timer(date: Date): Observable<Time> {
return Observable.interval(1000)
.map(() => this.createTimeObject(date))
}
}
Now use it in a Component:
import {Component, OnInit} from '@angular/core';
import {Time, TimerService} from '../timer.service';
@Component({
selector: 'app-timer',
template: `
<ng-container *ngIf="time1$ | async as time1"
<pre>{{time1.days}}days {{time1.hours}}hours {{time1.minutes}} minutes {{time1.seconds}}seconds<pre>
<br>
<ng-container>
<ng-container *ngIf="time2$ | async as time2"
<pre>{{time2.days}}days {{time2.hours}}hours {{time2.minutes}} minutes {{time2.seconds}}seconds<pre>
<br>
<ng-container>
`
})
export class TimerComponent implements OnInit {
time1$: Observable<Time>;
time2$: Observable<Time>;
constructor(private timerService: TimerService) {}
ngOnInit() {
this.time1$ = this.timerService.timer(new Date('June 4, 2020 15:37:25'))
this.time2$ = this.timerService.timer(new Date('August 9, 2041 15:37:25'))
}