问题描述
我有一个文件有几十个javascript函数。我想要做的是将该文件导入Angular 2组件并运行在external.js文件中定义的init()函数。
I have one file that have dozens javascript functions. What I want to do is to import that file into Angular 2 component and run init() function that is defined in "external.js" file.
import { Component, AfterViewInit } from '@angular/core';
import "../../../../assets/external.js";
@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class ComponentNameComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit(): void {
// invoke init() function from external.js file
}
}
external.js使用import和ngAfterViewInit()加载我想调用init() external.js中的函数调用该外部文件中的所有其他方法。
external.js is loaded using import and in ngAfterViewInit() I want to invoke init() function that is in external.js that calls all other methods in that external file.
这是external.js的一部分:
Here is part of external.js:
function init() {
callFunction1();
callFunction2();
}
推荐答案
您可以导入并声明您的外部对象。之后你可以在你的组件中使用它。
You can import and declare your external object. after then you can use it in your component.
import 'external.js'
declare var myExtObject: any;
我在plunker中做了一个例子:
I made an example in plunker:https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview
希望这会有所帮助。
这篇关于从Angular 2组件调用纯javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!