如何在 Angular 中包含 JavaScript 脚本文件并从该脚本调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44817349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:44:43  来源:igfitidea点击:

How do I include a JavaScript script file in Angular and call a function from that script?

javascriptangular

提问by Piyush Jain

I have a JavaScript file called abc.jsthat has a 'public' function called xyz(). I want to call that function in my Angular project. How do I do that?

我有一个 JavaScript 文件abc.js,它有一个名为xyz(). 我想在我的 Angular 项目中调用该函数。我怎么做?

采纳答案by Aravind

Refer the scripts inside the angular-cli.json(angular.jsonwhen using angular 6+) file.

请参阅angular-cli.jsonangular.json使用 angular 6+ 时)文件中的脚本。

"scripts": [
    "../path" 
 ];

then add in typings.d.ts(create this file in srcif it does not already exist)

然后添加typings.d.tssrc如果该文件尚不存在,则创建该文件)

declare var variableName:any;

Import it in your file as

将其导入到您的文件中

import * as variable from 'variableName';

回答by Rahul Singh

In order to include a global library, eg jquery.jsfile in the scripts array from angular-cli.json(angular.jsonwhen using angular 6+):

为了包含全局库,例如jquery.js脚本数组中的文件angular-cli.jsonangular.json使用 angular 6+ 时):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

之后,如果 ng serve 已经启动,请重新启动。

回答by Nagnath Mungade

Add external js file in index.html.

index.html 中添加外部 js 文件。

<script src="./assets/vendors/myjs.js"></script>

Here's myjs.jsfile :

这是myjs.js文件:

var myExtObject = (function() {

    return {
      func1: function() {
        alert('function 1 called');
      },
      func2: function() {
        alert('function 2 called');
      }
    }

})(myExtObject||{})


var webGlObject = (function() { 
    return { 
      init: function() { 
        alert('webGlObject initialized');
      } 
    } 
})(webGlObject||{})

Then declare it is in component like below

然后声明它在如下组件中

demo.component.ts

演示.component.ts

declare var myExtObject: any;
declare var webGlObject: any;

constructor(){
    webGlObject.init();
}

callFunction1() {
    myExtObject.func1();
}

callFunction2() {
    myExtObject.func2();
}

demo.component.html

演示.component.html

<div>
    <p>click below buttons for function call</p>
    <button (click)="callFunction1()">Call Function 1</button>
    <button (click)="callFunction2()">Call Function 2</button>
</div>

It's working for me...

它对我有用...

回答by crash

You can either

你可以

import * as abc from './abc';
abc.xyz();

or

或者

import { xyz } from './abc';
xyz()