[英]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.