【问题标题】:Call pure javascript function from Angular 2 component从 Angular 2 组件调用纯 javascript 函数
【发布时间】:2018-11-02 14:23:25
【问题描述】:

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

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

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

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

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

    希望这会有所帮助。

    【讨论】:

    • 我按照你的例子。我创建了 var webGlObject = (function() { return { init: function() { init(); } } })(webGlObject||{}) 并在 ngAfterViewInit() 中尝试使用 `webGlObject.init();` 进行访问,但我收到错误 errors.service.ts:29 ReferenceError: webGlObject is not defined
    • 我已经用你的 webGlObject 更新了 plunker,它正在工作。我唯一改变的是你在 init 函数中调用 init()。
    • 如果您仍然遇到错误,您能否提供更多信息或在例如 plunker、jsfiddle 或其他东西中创建?
    • 问题是因为我的脚本 external.js 是按照我上面描述的方式导入的。我将它移动到 index.html 并通过
    • 当您将 js 文件移动到 index.html 时,此脚本似乎会运行。但是浏览器仍然抱怨ReferenceError: webGlObject is not defined。我的解决方案是将scripts下的所有JS文件添加到angular-cli.json
    【解决方案2】:

    检查我的 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。谢谢你:)
    • 获取error TS2339: Property 'gajender' does not exist on type '{ (options: any): never; get: (options: any, callback: any) => void; getPromise: (options: any) =...'.
    • 未定义定义
    猜你喜欢
    • 2019-03-01
    • 2017-06-17
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多