从typescript angular 2调用javascript函数

时间:2017-04-20 21:18:46

标签: visual-studio angular typescript

我使用VS 2015作为我的IDE。我看过以下内容: Angular 2 typescript invoke javascript function

Using a Javascript Function from Typescript

Using a Javascript Function from Typescript

然而,我仍然没有得到基本的。

假设我有testing.js 和app.component.ts

    var testJs = function () {
    this.asd = 123;

}

testJs.prototype.testing = function (param) {
    console.log(param);
}

如何在app.component.ts中使用testJ?目前我尝试了但失败了:

import { Component } from '@angular/core';
interface testJs {
    testing: Function;
}
declare var testJs: testJs;
@Component({
    selector: 'my-app',
    templateUrl: '/mainTemplate.html'
})
export class AppComponent {
    testJs.testing("adsf");
}

我尝试过以下操作但仍然无法正常工作。 enter image description here

我没有angular.cli。没有angular.cli可以做到吗?

3 个答案:

答案 0 :(得分:4)

终于找到了办法。

  1. 在你下载main.js文件的html文件中,在head标签中引用javascript文件 enter image description here

  2. 你的打字稿文件中的
  3. (在这种情况下我使用的是角度)执行以下操作:

  4. 一个。声明变量:

    湾在导出的类

    的构造函数中使用funciton
    import { Component } from '@angular/core';
    declare function testJs(): any;
    @Component({
        selector: 'my-app',
        templateUrl: '/mainTemplate.html'
    })
    
    export class AppComponent {
        user: string;
        constructor() {
            testJs.prototype.testFunction();
            this.user = "asdf";
            var x = 90;
        }
    }
    

答案 1 :(得分:3)

  1. 在哪里获取此PoJo。这个外部库吗?如果是的话,你需要将它包含在angular-cli中:

    testJS.js

  2. 您需要创建打字或至少创建虚拟类型:

    "scripts": [ "../node_modules/.../testJS.js" ],

  3. 您可以在

  4. 之后使用它

答案 2 :(得分:0)

我在eval()中使用
1)在main.js文件之前,放入javascript文件。
2)从您的打字稿文件的eval(“ testFunction()”)中使用angular。