I'm fairly new to Angular 2 and I started off with creating a clock for my app. I tried to stick to the official documentation tutorial.
Folder structure:
The CSS file is still empty and the HTML is not very spectacular:
<p>{{time | date:'HH:mm' }}</p>
The clock component itself looks like this:
import {Component} from "@angular/core";
import {ClockService} from "./clock.service";
@Component({
selector: 'clock',
templateUrl: './clock.component.html',
styleUrls: ['./clock.component.css']
})
export class Clock {
time: Date;
constructor(private clockService: ClockService) {
}
ngOnInit() {
this.clockService.getClock().subscribe(time => this.time = time);
}
}
The most important part, however, is the service, which looks like this:
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
@Injectable()
export class ClockService {
private clock: Observable<Date>;
constructor() {
this.clock = Observable.interval(1000).map(tick => new Date()).share();
}
getClock(): Observable<Date> {
return this.clock;
}
}
Basically, I need a general review since this is my very first approach. However, what I'm really curious about is if I get the usage of the Observable right. Is it correct to store it as a private field like shown above? Am I doing the .share()
correctly?