I want to have a date countdown like this:
http://codepen.io/garethdweaver/pen/eNpWBb
but in angular 2, I found this plunkr that adds 1 to a number each 500
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
Now use it in a Component:
import {Component, OnInit} from '@angular/core';
import {Time, TimerService} from '../timer.service';
@Component({
selector: 'app-timer',
template: `
{{time1.days}}days {{time1.hours}}hours {{time1.minutes}} minutes {{time1.seconds}}seconds
{{time2.days}}days {{time2.hours}}hours {{time2.minutes}} minutes {{time2.seconds}}seconds
`
})
export class TimerComponent implements OnInit {
time1$: Observable