从Angular 2组件中调用纯javascript函数

Call pure javascript function from Angular 2 component

本文关键字:javascript 函数 调用 Angular 组件      更新时间:2023-09-26

我有一个文件,有几十个javascript函数。我要做的是将该文件导入Angular 2的组件,并运行在"external.js"文件中定义的init()函数。

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的一部分:

function init() {
  callFunction1();
  callFunction2();
}

可以导入和声明外部对象。然后你就可以在你的组件中使用它了。

import 'external.js'
declare var myExtObject: any;

我在plunker中做了一个例子:https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview

Checkout我的angular 6 git项目-我在login组件中使用了这个-

https://github.com/gajender1995/Angular-HighChart-Auth

exter.js

define(["require", "exports"], function(require, exports){
   exports.value = "aaa";
   exports.gajender = function(){console.log(2)}; 
});

login.component.ts

 import * as MyModule from './exter.js';
 console.log('my value is', MyModule.gajender());

tsconfig Add

"allowJs": true

需要像这样导入javascript文件:

import * as myjsname from '../../mypathto/myjavascriptfile.js';

从javascript文件中调用一个例程,如下所示:

myjsname.myjsroutine();
重要的是,你需要在javascript文件中使用export关键字,像这样:
export function myjsroutine() {
  //my js code
}