簡體   English   中英

從Angular 2組件調用純javascript函數

[英]Call pure javascript function from Angular 2 component

我有一個文件,有幾十個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()加載我想調用external.js中的init()函數,該函數調用該外部文件中的所有其他方法。

這是external.js的一部分:

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

您可以導入和聲明外部對象。 之后,您可以在組件中使用它。

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

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

希望這可以幫助。

檢查我的角度6的git項目 - 我在登錄組件中使用了這個 -

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中添加

"allowJs": true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM