添加js文件 --Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';


declare const document: any;


@Injectable()
export class ScriptService {
  private loaded = false;
  private list: any = {};
  private emitter: Subject = new Subject();


  getChangeEmitter() {
    return this.emitter;
  }


  load(path: string[]) {
    if (this.loaded) return this;


    this.loaded = true;


    const promises: Promise[] = [];


    path.forEach(script => promises.push(this.loadScript(script)));


    Promise.all(promises).then(res => {
      this.emitter.next(true);
    });


    return this;
  }


  loadScript(path: string): Promise {
    return new Promise((resolve, reject) => {
      if (this.list[path] === true) {
        resolve({
          path: path,
          loaded: true,
          status: 'Loaded',
        });
        return;
      }


      this.list[path] = true;


      const node = document.createElement('script');
      node.type = 'text/javascript';
      node.src = path;
      node.charset = 'utf-8';
      if (node.readyState) {
        // IE
        node.onreadystatechange = () => {
          if (node.readyState === 'loaded' || node.readyState === 'complete') {
            node.onreadystatechange = null;
            resolve({
              path: path,
              loaded: true,
              status: 'Loaded',
            });
          }
        };
      } else {
        node.onload = () => {
          resolve({
            path: path,
            loaded: true,
            status: 'Loaded',
          });
        };
      }
      node.onerror = (error: any) =>
        resolve({
          path: path,
          loaded: false,
          status: 'Loaded',
        });
      document.getElementsByTagName('head')[0].appendChild(node);
    });
  }
}

你可能感兴趣的:(Angular)