Skip to content

Instantly share code, notes, and snippets.

@JohannesRudolph
Created May 7, 2017 16:53
Show Gist options
  • Save JohannesRudolph/87bf06aeaa0a94f1129fd0e0216be18f to your computer and use it in GitHub Desktop.
Save JohannesRudolph/87bf06aeaa0a94f1129fd0e0216be18f to your computer and use it in GitHub Desktop.
Angular lazy library loader
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