简体   繁体   English

从js文件导入的函数,不在TS文件中运行

[英]Imported function from js file, doesn't run in TS file

I'm trying to call a JS function inside a component in my TS file, but I'm getting an exception. 我正在尝试在TS文件中的组件内调用JS函数,但出现异常。

Component 零件

import '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new GanttMaster();
  }
}

Error: 错误:

Error referecences error: GanttMaster is not defined

You need to change the way you import the .js file: 您需要更改导入.js文件的方式:

import * as gantt from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new gantt.GanttMaster();
  }
}

If you want to use GanttMaster among several components, you can import the .js file in angular.json and declare a constant in app.module.ts like declare const GanttMaster: any . 如果你想使用GanttMaster几个组件中,你可以导入.js文件angular.json并声明常数app.module.tsdeclare const GanttMaster: any Then you can use it in your application. 然后,您可以在应用程序中使用它。

Hope this helps. 希望这可以帮助。


UPDATE UPDATE

Alternatively, you can import it the way you've already done, but declare the function manually before the import: 另外,您可以按照已经完成的方式导入它,但是在导入之前手动声明该函数:

declare const GanttMaster: any;
import from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new GanttMaster();
  }
}

Ref: https://stackoverflow.com/a/37084553/1331040 参考: https : //stackoverflow.com/a/37084553/1331040

In my project i load a js file from assets, something like this: 在我的项目中,我从资产加载js文件,如下所示:

add this JavaScript file in scripts array in angular.json file like as above you have added jquery library. 将此JavaScript文件添加到angular.json文件的scripts数组中,就像上面已经添加了jquery库一样。

"scripts": [
  .....
  "src/assets/js/custom.js"
]

custom.js: custom.js:

function myTest() {
    alert('Welcome to custom js');
}

You need declare in your component 您需要在组件中声明

declare const myTest: any;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM