LP1888723 Angular File exporter service
authorBill Erickson <berickxx@gmail.com>
Tue, 23 Jun 2020 20:57:07 +0000 (16:57 -0400)
committerGalen Charlton <gmc@equinoxOLI.org>
Sun, 15 Aug 2021 23:54:40 +0000 (19:54 -0400)
Package up some of the nitty gritty of supporting file exports from the
Angular client into a utility service.

Signed-off-by: Bill Erickson <berickxx@gmail.com>
Signed-off-by: Ruth Frasur <rfrasur@library.in.gov>
Signed-off-by: Galen Charlton <gmc@equinoxOLI.org>
Open-ILS/src/eg2/src/app/share/util/file-export.service.ts [new file with mode: 0644]

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 (file)
index 0000000..c2a8ef2
--- /dev/null
@@ -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<any> {
+
+        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;
+    }
+}
+