import { Component, Inject, InjectionToken, Input, OnChanges, OnDestroy, OnInit, PLATFORM_ID, SimpleChanges } from "@angular/core"; import {Report} from "./cache-indicators"; import {CacheIndicatorsService} from "./cache-indicators.service"; import {interval, Subject, Subscription} from "rxjs"; import {map, switchMap, takeUntil} from "rxjs/operators"; import {isPlatformBrowser} from "@angular/common"; @Component({ selector: 'cache-indicators', template: `
`, styleUrls: ['cache-indicators.component.less'] }) export class CacheIndicatorsComponent implements OnInit, OnChanges, OnDestroy { report: Report; subscriptions: Subscription[] = []; interval: number = 10000; readonly destroy$ = new Subject(); @Input() alias: string; constructor(private cacheIndicatorsService: CacheIndicatorsService, @Inject(PLATFORM_ID) private platformId: any) { } ngOnInit() { this.getReport(); } ngOnChanges(changes: SimpleChanges) { if (changes.alias) { this.clear(); this.getReport(); } } getReport() { this.subscriptions.push(this.cacheIndicatorsService.getReport(this.alias).subscribe(report => { this.getReportInterval(report); }, error => { this.report = null; })); } getReportInterval(report: Report) { if (this.isBrowser && (this.report || !report?.completed)) { this.report = report; this.subscriptions.push(interval(this.interval).pipe( map(() => this.cacheIndicatorsService.getReport(this.alias)), switchMap(report => report), takeUntil(this.destroy$)). subscribe(report => { this.report = report; if (this.report.completed) { this.destroy$.next(); } })); } } clear() { this.subscriptions.forEach(subscription => { if (subscription instanceof Subscription) { subscription.unsubscribe(); } }); this.report = null; } get isBrowser() { return isPlatformBrowser(this.platformId); } ngOnDestroy() { this.clear(); } }