Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calendar pipe: wrap setTimeout with outsideAngularApp #135

Merged
merged 5 commits into from
Mar 18, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions src/calendar.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,15 @@ export class CalendarPipe implements PipeTransform, OnDestroy {

constructor(private cdRef: ChangeDetectorRef, private ngZone: NgZone) {
// using a single static timer for all instances of this pipe for performance reasons
CalendarPipe.initTimer();
CalendarPipe.initTimer(ngZone);

CalendarPipe.refs++;

// values such as Today will need to be replaced with Yesterday after midnight,
// so make sure we subscribe to an EventEmitter that we set up to emit at midnight
this.ngZone.runOutsideAngular(() =>
this.midnightSub = CalendarPipe.midnight.subscribe(() => {
this.ngZone.run(() => this.cdRef.markForCheck());
}));
this.midnightSub = CalendarPipe.midnight.subscribe(() => {
this.ngZone.run(() => this.cdRef.markForCheck());
});
}

transform(value: Date | moment.Moment, ...args: any[]): any {
Expand Down Expand Up @@ -64,20 +63,22 @@ export class CalendarPipe implements PipeTransform, OnDestroy {
this.midnightSub.unsubscribe();
}

private static initTimer() {
private static initTimer(ngZone: NgZone) {
// initialize the timer
if (!CalendarPipe.midnight) {
CalendarPipe.midnight = new EventEmitter<Date>();
if (typeof window !== 'undefined') {
let timeToUpdate = CalendarPipe._getMillisecondsUntilUpdate();
CalendarPipe.timer = window.setTimeout(() => {
// emit the current date
CalendarPipe.midnight.emit(new Date());

// refresh the timer
CalendarPipe.removeTimer();
CalendarPipe.initTimer();
}, timeToUpdate);
CalendarPipe.timer = ngZone.runOutsideAngular(() => {
return window.setTimeout(() => {
// emit the current date
CalendarPipe.midnight.emit(new Date());

// refresh the timer
CalendarPipe.removeTimer();
CalendarPipe.initTimer(ngZone);
}, timeToUpdate);
});
}
}
}
Expand Down