【问题标题】:calling javascript function from typescript angular 2从打字稿角度2调用javascript函数
【发布时间】:2017-04-20 21:18:45
【问题描述】:

我使用 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 中使用 testJs?目前我尝试这个但失败了:

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");
}

我尝试了以下方法,但仍然无法正常工作。

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

【问题讨论】:

  • 你看过这里的 Angular 测试指南吗:angular.io/docs/ts/latest/testing
  • 我不是在寻找单元测试。我正在寻找如何从打字稿调用 javascript 函数
  • 你在使用 angular-cli 吗?你需要把这个脚本放到 angular-cli.json 文件中吗?
  • 不,我不使用 angular-cli。有没有无需使用 Angular cli 的解决方案?

标签: visual-studio angular typescript


【解决方案1】:

终于找到了办法。

  1. 在您下载 main.js 文件的 html 文件中,将 javascript 文件的引用放在 head 标记中

  2. 在您的打字稿文件(在这种情况下我使用 angular)中执行以下操作:

一个。声明变量:

b.在导出类的构造函数中使用函数

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;
    }
}

【讨论】:

  • 刷新后我总是得到未定义的错误。你知道有什么解决办法吗?
  • 声明函数 testJs(): any;在上述上下文中, testJs 不是文件名。它是函数名。你猜对了吗?
  • 那么“testFunction()”是什么?
  • 只是一些随机函数。你可以用任何名字来改变它
【解决方案2】:
  1. 在哪里得到这个testJS.js。这是外部库吗?如果是,您需要像这样将它包含在 angular-cli 中:

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

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

    declare var testJS: any;

  3. 以后可以用了

【讨论】:

  • 我认为它不起作用...我只是在上面的问题中放了一个屏幕截图
  • 为 js 文件创建类型?怎么样,拜托!
【解决方案3】:

我使用的是 eval()
1) 在 main.js 文件之前,放置 javascript 文件。
2)在你的打字稿文件中使用 eval("testFunction()") 角度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2019-08-10
    • 2018-11-11
    相关资源
    最近更新 更多