简体   繁体   English

从Angular 2组件调用纯javascript函数

[英]Call pure javascript function from Angular 2 component

I have one file that have dozens javascript functions. 我有一个文件,有几十个javascript函数。 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. 我想要做的是将该文件导入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 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使用import和ngAfterViewInit()加载我想调用external.js中的init()函数,该函数调用该外部文件中的所有其他方法。

Here is part of external.js: 这是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;

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

Hope this helps. 希望这可以帮助。

Checkout my git project of angular 6 - I used this in login component - 检查我的角度6的git项目 - 我在登录组件中使用了这个 -

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

exter.js exter.js

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

login.component.ts login.component.ts

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

 console.log('my value is', MyModule.gajender());

In tsconfig Add tsconfig中添加

"allowJs": true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM