如何在angular中加载动态脚本

时间:2019-03-08 20:03:31

标签: angular typescript frontend

角度:7.1.4

我试图解决加载脚本的问题,因为出现了错误Uncaught TypeError: Can not read property响应式'undefined`。我发现了一种可能的解决方案,该解决方案是创建一个服务以动态加载脚本。我按照本教程进行了所有工作,以使其正常运行,但无法正常工作。

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

interface Scripts {
  name: string;
  src: string;
}

export const ScriptStore: Scripts[] = [
  { name: 'jquery', src: 'https://code.jquery.com/jquery-3.3.1.min.js' },
  { name: 'tables', src: '../../../assets/dashboard/js/tables.js' },
  { name: 'widgets', src: '../../../assets/dashboard/js/widgets.js' },
  { name: 'charts', src: '../../../assets/dashboard/js/charts.js' },
  { name: 'theme.min', src: '../../../assets/dashboard/dist/js/theme.min.js'}
];

declare var document: any;

@Injectable()
export class DynamicScriptLoaderService {

  private scripts: any = {};

  constructor() {
    ScriptStore.forEach((script: any) => {
      this.scripts[script.name] = {
        loaded: false,
        src: script.src
      };
    });
  }

  load(...scripts: string[]) {
    const promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
  }

  loadScript(name: string) {
    return new Promise((resolve, reject) => {
      if (!this.scripts[name].loaded) {
        //load script
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.scripts[name].src;
        if (script.readyState) {  //IE
            script.onreadystatechange = () => {
                if (script.readyState === "loaded" || script.readyState === "complete") {
                    script.onreadystatechange = null;
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
                }
            };
        } else {  //Others
            script.onload = () => {
                this.scripts[name].loaded = true;
                resolve({script: name, loaded: true, status: 'Loaded'});
            };
        }
        script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
        document.getElementsByTagName('head')[0].appendChild(script);
      } else {
        resolve({ script: name, loaded: true, status: 'Already Loaded' });
      }
    });
  }
}

然后,我尝试在组件初始化时调用此服务以加载脚本

ngOnInit() {
    this.loadScripts();
  }

  private loadScripts() {
    // You can load multiple scripts by just providing the key as argument into load method of the service
    this.dynamicScriptLoader.load(
      'jquery',
      'tables',
      'widgets',
      'charts',
      'theme.min'
      )
      .then(data => {
        console.log('scripts loaded')
    }).catch(error => console.log(error));
  }

使用此服务时遇到的错误有几种,除了继续出现与以前相同的错误外,其他错误也从文件图表中显示为Failed to load resource: the server responded with a status of 404 (Not Found)Uncaught ReferenceError: c3 is not defined,以及类似的错误。我看过一些看起来不错的教程,可能是从该服务打错了电话。

1 个答案:

答案 0 :(得分:0)

好吧..我重新编码了许多HTML,并且可能我两次调用了一些脚本js。.