|
| 1 | +import {ChangeDetectionStrategy, Component, Injector, Input} from '@angular/core'; |
| 2 | +import {interval} from 'rxjs/observable/interval'; |
| 3 | +import {map} from 'rxjs/operators'; |
| 4 | +import {Subscription} from 'rxjs/Subscription'; |
| 5 | +import {Observable} from 'rxjs/Observable'; |
| 6 | +import {TreeNode} from '../../../common/tree-node.class'; |
| 7 | +import {Lifecycle} from '../../../common/utils/Lifecycle'; |
| 8 | + |
| 9 | +@Component({ |
| 10 | + selector: 'interval', |
| 11 | + templateUrl: './interval.component.html', |
| 12 | + styleUrls: ['./interval.component.css'], |
| 13 | + changeDetection: ChangeDetectionStrategy.Default |
| 14 | +}) |
| 15 | +@Lifecycle({defaultName: true}) |
| 16 | +export class IntervalComponent extends TreeNode { |
| 17 | + @Input() public runOutside: string; |
| 18 | + @Input() public setInterval: string; |
| 19 | + @Input() public asyncPipe: string; |
| 20 | + public enabled: boolean; |
| 21 | + public formatDate: string; |
| 22 | + public timerSub: Subscription; |
| 23 | + public timerObservable: Observable<string>; |
| 24 | + public timer: number; |
| 25 | + |
| 26 | + constructor(context: Injector) { |
| 27 | + super(context); |
| 28 | + this.formatDate = this.getFormattedDate(); |
| 29 | + } |
| 30 | + |
| 31 | + public enableInterval() { |
| 32 | + if (this.setInterval) { |
| 33 | + this.timerInterval(); |
| 34 | + } else if (this.runOutside) { |
| 35 | + this.zone.runOutsideAngular(() => { |
| 36 | + const timer = interval(1000).pipe(map(this.getFormattedDate)); |
| 37 | + this.timerSub = timer.subscribe((time) => { |
| 38 | + this.formatDate = time; |
| 39 | + this.cd.detectChanges(); |
| 40 | + }); |
| 41 | + }); |
| 42 | + } else { |
| 43 | + this.zone.runOutsideAngular(() => { // but async pipe execute main zone |
| 44 | + this.timerObservable = interval(1000).pipe(map(this.getFormattedDate)); |
| 45 | + }); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public updateInterval(enable: boolean) { |
| 50 | + if (enable) { |
| 51 | + this.enableInterval(); |
| 52 | + } else { |
| 53 | + if (this.timerSub) { |
| 54 | + this.timerSub.unsubscribe(); |
| 55 | + } |
| 56 | + this.timerObservable = null; |
| 57 | + clearInterval(this.timer); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private timerInterval() { |
| 62 | + this.timer = window.setInterval(() => { |
| 63 | + this.formatDate = this.getFormattedDate(); |
| 64 | + this.cd.detectChanges(); |
| 65 | + }, 1000); |
| 66 | + } |
| 67 | + |
| 68 | + private getFormattedDate() { |
| 69 | + return new Date().toJSON().substring(10, 19).replace('T', ''); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments