【问题标题】:How to add and use custom js file in Angular 2 App in TypeScript components如何在 TypeScript 组件中的 Angular 2 App 中添加和使用自定义 js 文件
【发布时间】:2017-06-27 13:02:35
【问题描述】:

我用 angular-cli 创建了非常标准的 Angular 2 应用程序

我希望能够使用自定义 .js 文件。 简化的模拟版本如下所示:

'use strict';

var testingThing = testingThing || {};

testingThing.Client = function (name) {
    var self = this;
    console.log(name);

    this.parseUri = function (str) {
        console.log(str);
        return str;
    };

    return this;
};

// Node environment module
if (typeof window === 'undefined') {
    module.exports = testingThing;
}

我正在努力如何在打字稿组件中使用它。

我试过这个(或类似的,也试过不同的东西)

export class TestService {

  something: any;

  constructor() {
    this.something = new testingThing.Client();
    var huh = this.something.new("test name");
    testingThing.parseUri("testParse");
  }

}

我尝试为它生成类型

declare namespace testingThing{

    class Client {
        new (name : string): /* testingThing.Client */ any;
    }

    function parseUri(str : any): any;
}

但后来我在控制台中遇到错误,未定义 testingThing。

 Cannot read property 'Client' of undefined

当我尝试导入它时,它说 testingThing 不是一个模块。

我确实将 myCustom.js 添加到 angular-cli.json

"scripts": [
        "./myCustom.js"
      ],

我从互联网上尝试了几种不同的方法,所以我现在完全没有想法,我做错了什么。是我对它的使用,我的打字定义,还是其他什么。

我希望答案对于那些更习惯于前端编程的人来说是显而易见的,但我现在很困惑。

【问题讨论】:

    标签: javascript angularjs typescript typescript-typings external-dependencies


    【解决方案1】:

    这就是我让它工作的方式,所以如果你和我有同样的问题并在这里发布这个 Q,那么希望它也能帮助你:)(不确定它是否正确,但它对我有用) .这是一次偶然的探索。很多失误,最后一击:

    1. 在 index.html 中的<script></script> 标记中包含您的自定义脚本,如下所示:

      <script src="./myCustom.js"></script>
      
    2. 打字应该改变:

      • 类而不是接口
      • 构造函数而不是新方法(还需要删除返回值声明)
    declare namespace testingThing 
    {
    
          class Client {
    
            constructor(name: string)
          }
    
          function testFunction(str: any): string;}
    

    然后示例用法将是:

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class TestService {
    
      somethingElse: any;
    
      constructor() {
        this.somethingElse = new testingThing.Client("constructor");
        console.log(this.somethingElse);
        this.somethingElse.testFunction("test call to function inside");
      }
    
    }
    

    没有任何导入、“要求”或变量声明。

    此外,您应该从脚本部分中的 angular-cli.json 中删除您的库(或者无论如何都不包含它)。不需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 2017-05-18
      相关资源
      最近更新 更多