import { Injectable } from '@angular/core'; import { RdLib } from "../base/rdLib"; declare const jQuery: any; export interface StyleItem { src: string; loaded: boolean; } export interface Styles { [key: string]: StyleItem } @Injectable() export class StyleLoaderService { private _styles: Styles = {}; load(styles: Array, loadOnce = true, tag = "body") { let promises: any[] = []; styles.forEach((script) => promises.push(this.loadStyle(script, loadOnce, tag))); return Promise.all(promises); } remove(styles: Array, tag = "body") { styles.forEach(src => { if (!this._styles[src]) { RdLib.screenOperations.toastr.warning("Style src=" + src + " is not loaded"); } else { jQuery(tag).find("link").filter((_, item) => { return item.outerHTML == '' }).remove(); this._styles[src] = { src: src, loaded: false }; } }); } private loadStyle(src: string, loadOnce: boolean, tag: string): Promise { if (!this._styles[src]) { this._styles[src] = { src: src, loaded: false }; } return new Promise(function (resolve, reject) { // resolve if already loaded if (this._styles[src].loaded && loadOnce) { resolve({ src: src, loaded: true }); } else { // load style tag let styleTag = jQuery(''). attr('type', 'text/css'). attr('rel', 'stylesheet'). attr('href', this._styles[src].src); jQuery(tag).append(styleTag); this._styles[src] = { src: src, loaded: true }; resolve({ src: src, loaded: true }); } }.bind(this)); } }