[英]Loading 3rd party JS files to angular components files
我已经将第3方js文件加载到了app.component中,就像这样
declare var MarvinJS: any;
import { MarvinJS } from "../assets/js/marvinjslauncher.js";
我可以在我的应用程序组件类中使用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)
根据我们在评论中进行的讨论,这里有一些事情可以解决此问题以及代码中的其他问题:
首先,将MarvinJs
js文件包含为<script>
,并确保您可以在控制台中访问MarvinJs
命名空间和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){});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.