从Angular 2组件调用纯JavaScript函数

28

我有一个文件,其中包含几十个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
    }
}

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

以下是external.js的部分内容:

function init() {
  callFunction1();
  callFunction2();
}
3个回答

44

2
我按照您的示例创建了 `var webGlObject = (function() {return { init: function() { init(); } }})(webGlObject||{}) 并在ngAfterViewInit()中尝试使用webGlObject.init();访问,但是出现了错误errors.service.ts:29 ReferenceError: webGlObject is not defined`。 - Haris Hajdarevic
我已经将您的webGL对象更新到plunker中,并且它正在运行。我唯一改变的就是在init函数中调用了init()。 - hakany
3
问题是因为我的 external.js 脚本是按照我之前描述的方式导入的。我将它移动到 index.html 中,并通过头部的 <script> 标签进行包含。之后它开始工作了。谢谢 @hakany。 - Haris Hajdarevic
我按照你的示例操作,但是出现了 TypeError: pm.loading 不是一个函数 的错误。loading 基本上是从 plnkr 示例中的 func1 函数中调用的。 - Kutas Tomy
在 Angular 4 和 5 中,您可以使用以下方式导入 JavaScript:import {filename} '../file/location/filename.js'; - Jnr
显示剩余3条评论

7

请查看我的Angular 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

谢谢你的出色回答,伙计。顺便说一下,没有在tsconfig.json中添加“allowJs” true也可以工作。谢谢 :) - Anjana Silva
获取 error TS2339: 属性 'gajender' 在类型 '{ (options: any): never; get: (options: any, callback: any) => void; getPromise: (options: any) => Promise<...>; }' 上不存在。 - Toolkit
定义未定义。 - Yasar Arafath

0
你需要像这样导入javascript文件:
import * as myjsname from '../../mypathto/myjavascriptfile.js';

你可以像这样从javascript文件中调用一个例程:
myjsname.myjsroutine();

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接