From 163948620c7d03c278f6a429d794be97a3d4c602 Mon Sep 17 00:00:00 2001 From: Bill Erickson Date: Tue, 23 Jun 2020 16:57:07 -0400 Subject: [PATCH] LP1888723 Angular File exporter service Package up some of the nitty gritty of supporting file exports from the Angular client into a utility service. Signed-off-by: Bill Erickson Signed-off-by: Ruth Frasur Signed-off-by: Galen Charlton --- .../eg2/src/app/share/util/file-export.service.ts | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Open-ILS/src/eg2/src/app/share/util/file-export.service.ts diff --git a/Open-ILS/src/eg2/src/app/share/util/file-export.service.ts b/Open-ILS/src/eg2/src/app/share/util/file-export.service.ts new file mode 100644 index 0000000000..c2a8ef24b2 --- /dev/null +++ b/Open-ILS/src/eg2/src/app/share/util/file-export.service.ts @@ -0,0 +1,54 @@ +/** + * Create and consume BroadcastChannel broadcasts + */ +import {Injectable, EventEmitter} from '@angular/core'; +import {DomSanitizer, SafeUrl} from '@angular/platform-browser'; +import {empty} from 'rxjs'; + +@Injectable() +export class FileExportService { + + resolver: Function = null; + safeUrl: SafeUrl; + + constructor(private sanitizer: DomSanitizer) { } + + exportFile($event: any, content: string, + contentType: string = 'text/plain'): Promise { + + if (!$event || !content) { return null; } + + if (this.resolver) { + // This is secondary href click handler. Give the + // browser a moment to start the download, then reset + // the CSV download attributes / state. + setTimeout(() => { + this.resolver(); + this.resolver = null; + this.safeUrl = null; + }, 500); + + return; + } + + const promise = new Promise(resolve => this.resolver = resolve); + const blob = new Blob([content], {type : contentType}); + const win: any = window; // avoid TS errors + + this.safeUrl = this.sanitizer.bypassSecurityTrustUrl( + (win.URL || win.webkitURL).createObjectURL(blob)); + + // Fire the 2nd click event now that the browser has + // information on how to download the CSV file. + setTimeout(() => $event.target.click()); + + $event.preventDefault(); + + return promise; + } + + inProgress(): boolean { + return this.resolver !== null; + } +} + -- 2.11.0