Created
July 3, 2020 04:53
-
-
Save thaylongs/c759291641f3a191e90f5200e92b4628 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from '@angular/core'; | |
export type ScriptsNames = 'pdfMake' | 'vfsFonts' | |
interface Scripts { | |
name: ScriptsNames; | |
src: string; | |
} | |
export const ScriptStore: Scripts[] = [ | |
{name: 'pdfMake', src: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.64/pdfmake.min.js'}, | |
{name: 'vfsFonts', src: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.64/vfs_fonts.js'} | |
]; | |
// Explicação base | |
// https://www.ngdevelop.tech/loading-external-libraries-from-cdn-in-angular-application/ | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class ScriptService { | |
private scripts: { [name: string]: { loaded: boolean, src: string } } = {}; | |
constructor() { | |
ScriptStore.forEach((script: Scripts) => { | |
this.scripts[script.name] = { | |
loaded: false, | |
src: script.src | |
}; | |
}); | |
} | |
load(...scripts: ScriptsNames[]) { | |
const promises: any[] = []; | |
scripts.forEach((script) => promises.push(this.loadScript(script))); | |
return Promise.all(promises); | |
} | |
loadScript(name: string): Promise<{ loaded: boolean, script: string, status: string }> { | |
return new Promise((resolve, reject) => { | |
// resolve if already loaded | |
if (this.scripts[name].loaded) { | |
resolve({script: name, loaded: true, status: 'Already Loaded'}); | |
} else { | |
// load script | |
const script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = this.scripts[name].src; | |
script.onload = () => { | |
this.scripts[name].loaded = true; | |
console.log(`${name} Loaded.`); | |
resolve({script: name, loaded: true, status: 'Loaded'}); | |
}; | |
script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'}); | |
document.getElementsByTagName('head')[0].appendChild(script); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment