从Angular 2组件调用纯javascript函数

Har*_*vic 25 javascript angular

我有一个文件,有几十个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
    }
}
Run Code Online (Sandbox Code Playgroud)

external.js使用import和ngAfterViewInit()加载我想调用external.js中的init()函数,该函数调用该外部文件中的所有其他方法.

这是external.js的一部分:

function init() {
  callFunction1();
  callFunction2();
}
Run Code Online (Sandbox Code Playgroud)

hak*_*any 40

您可以导入和声明外部对象.之后,您可以在组件中使用它.

import 'external.js'
declare var myExtObject: any;
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助.

  • 问题是因为我的脚本external.js是按照我上面描述的方式导入的.我将它移动到index.html并通过标题中的<script>标记包含它.之后它开始工作.谢谢你@hakany (3认同)
  • 我按照你的榜样.我创建了`var webGlObject =(function(){return {init:function(){init();}}})(webGlObject || {})`和ngAfterViewInit()试图用`webGlObject.init()访问;`但我收到错误`errors.service.ts:29 ReferenceError:webGlObject未定义 (2认同)

Gaj*_*ngh 7

检查我的 angular 6 git 项目 - 我在登录组件中使用了它 -

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

外部.js

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

登录.component.ts

 import * as MyModule from './exter.js';

 console.log('my value is', MyModule.gajender());
Run Code Online (Sandbox Code Playgroud)

tsconfig添加

"allowJs": true
Run Code Online (Sandbox Code Playgroud)