将第三方JS文件加载到角度组件文件

时间:2017-05-05 20:04:27

标签: javascript angular typescript

我已将第三方js文件加载到app.component中,如此

declare var MarvinJS: any;
import { MarvinJS } from "../assets/js/marvinjslauncher.js";

我可以使用我的app组件类中的marvinjslauncher.js中定义的方法,如果是,请指导我如何使用?我试过这样用:

export class AppComponent {
  constructor() {
      MarvinJS.MarvinJSUtil.getEditor("#sketch").then(function(sketcherInstance){
            });
}

如果我导入的方式有误,请你指导我。我还将marvinjslauncher.js文件包含在index.itml中 我遇到了这种错误:

ERROR TypeError: Cannot read property 'MarvinJSUtil' of undefined
    at new AppComponent (eval at <anonymous> (bundle.js:1312), <anonymous>:16:39)
    at createClass (eval at <anonymous> (bundle.js:321), <anonymous>:11007:26)
    at createDirectiveInstance (eval at <anonymous> (bundle.js:321), <anonymous>:10841:37)
    at createViewNodes (eval at <anonymous> (bundle.js:321), <anonymous>:12204:49)
    at createRootView (eval at <anonymous> (bundle.js:321), <anonymous>:12109:5)
    at callWithDebugContext (eval at <anonymous> (bundle.js:321), <anonymous>:13247:42)
    at Object.debugCreateRootView [as createRootView] (eval at <anonymous> (bundle.js:321), <anonymous>:12707:12)
    at ComponentFactory_.create (eval at <anonymous> (bundle.js:321), <anonymous>:10030:46)
    at ComponentFactoryBoundToModule.create (eval at <anonymous> (bundle.js:321), <anonymous>:3633:29)
    at ApplicationRef_.bootstrap (eval at <anonymous> (bundle.js:321), <anonymous>:5214:57)

1 个答案:

答案 0 :(得分:0)

基于我们在评论中的讨论,有一些方法可以解决这个问题以及代码中的其他问题:

首先,将您的MarvinJs js文件包含为<script>,并确保您可以在控制台中访问MarvinJs命名空间和实用程序。

然后,在你的app.component.ts文件中

declare var MarvinJS: any; // keep
// remove this import
//import { MarvinJS } from "../assets/js/marvinjslauncher.js";

export class AppComponent implements AfterViewInit { // implement AfterViewInit

  constructor() {} // remove MarvinJs code from constructor

  ngAfterViewInit(){
       // move MarvinJs code from constructor to ngAfterViewInit method. read about AfterViewInit here: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
       MarvinJS.MarvinJSUtil
      .getEditor("#sketch")
      .then(function(sketcherInstance){});
  }