-
-
Save sasha7/e6797099b67204f9ec5e87f844bab354 to your computer and use it in GitHub Desktop.
Angular lazy library loader
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, Inject } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import { ReplaySubject } from 'rxjs/ReplaySubject'; | |
import { DOCUMENT } from '@angular/platform-browser'; | |
@Injectable() | |
export class LazylibsService { | |
private chartJs?: ReplaySubject<any>; | |
// see http://stackoverflow.com/questions/37521298/how-to-inject-document-in-angular-2-service | |
// can't use Document type here due to: https://github.com/angular/angular/issues/12631 | |
constructor(@Inject(DOCUMENT) private readonly document: any) { } | |
public loadChartsJs(): Observable<any> { | |
if (this.chartJs) { | |
return this.chartJs.asObservable(); | |
} | |
this.chartJs = new ReplaySubject(); | |
const script = this.document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = '/lazylib/Chart.bundle.min.js'; | |
script.onload = () => { | |
this.chartJs!.next(''); | |
this.chartJs!.complete(); | |
}; | |
this.document.body.appendChild(script); | |
return this.chartJs.asObservable(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment