angular 4 如何在外部js中调用一个函数

angular4 how to call a function in a external js

我有一个将日志显示到控制台的 jscript:

x.js 包含

function open() {
    console.log('this a function');
}

在我的应用index.html中

<script src="x.js"></script>

在我的组件中

declare var xJS : any;;

@Component({
   selector: 'employerfile',
   templateUrl: './employerfile.component.html'
})

export class EmployerFileComponent
    .....
    openURL() {
       xJS.open();  
    }
}

在html

<a (click)="openURL()"> click </a>

当我执行这段代码时,我得到一个异常@

Original exception: xJS is not defined

如何调用这个外部函数?

您应该首先像这样导入它:

import * as xJS from 'xJS';

像这样导入文件 <script src="x.js"></script> 将不起作用。

您必须按以下方式导入它:

import * as xJS from './x.js';

如果不起作用,另一种方法是使用 System.import:

declare var System: any; 

System.import('./x.js')
    .then(xJS => {
        xJS.open();
    });

您可以查看以下内容

您必须声明要在 angular 组件中使用的函数的名称,如-

declare var open: any;

这基本上告诉编译器 open 存在于某处,然后将在您的 js 文件中找到。

此外,要在您的组件中使用上述方法,您必须使用此语法-

anyCustomMethodName/anyLifeCycleMethod() {
    new open();
}

如果您的 x.js 文件不在您的本地计算机上或托管在 CDN 上或它是第三方库,则您无法通过上述方式导入它。 甚至 System.import 已弃用.

您可以将 js 文件添加到 index.html 并使用 window 全局对象调用其函数我们早点做。