【问题标题】:How can I re-execute an external script in Angular?如何在 Angular 中重新执行外部脚本?
【发布时间】:2017-10-19 19:20:08
【问题描述】:

我有一个外部 js 文件,其中包含一组用于用户界面的 jQuery 方法。但是,Angular 路由器是异步的,因此脚本无法正确呈现其他页面上的用户界面元素,因为它们尚不存在于 DOM 中。

以前,我会从脚本中挑选一些方法并将它们添加到名为 rerender 的方法中,但这变得越来越混乱。

我的问题是看看是否有办法在rerender 方法中再次加载和执行整个脚本?

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

    您可以导入外部脚本。在构造函数中执行:

    constructor() {
        System.import('script-loader!bower_components/fullcalendar/dist/fullcalendar.min.js').then(()=>{
          this.render(); // Do whatever, for demonstration I call a render() method
        })
    }
    

    确保在您的custom-typings 中声明了System

    declare let System: SystemJS;
    
    interface SystemJS {
      import: (path?: string) => Promise<any>;
    }
    
    interface GlobalEnvironment {
      SystemJS: SystemJS;
      System: SystemJS;
    }
    

    选项 2:

    或者,您可以在导入语句之后将其放入模块中:

    require('bootstrap/js/tooltip.js'); // For example
    

    【讨论】:

    • 我正在使用 Angular CLI,据我所知,它不使用 System,但我可能是错的。你能用 Angular CLI 验证这一点吗?
    • 它使用它。我也有 Angular-CLI! :D
    • 它似乎不起作用。导入正在执行,但据我所知脚本无法正常工作。
    • 检查您的自定义类型是否已声明 System,就像我在更新的答案中发布的那样。如果脚本正在加载,请在控制台中检查。
    • 完美,有效。只是有一个不同页面的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2017-06-09
    • 2013-07-01
    • 2016-07-10
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多