0

添加和使用自定义的js文件我有非常标准的角2应用程序与角CLI如何角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角cli.json

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

我试过几个来自互联网不同的方法,所以我现在是完全的想法,我在做什么错。这是我对它的用法,我的打字定义,还是其他任何东西。

我希望答案是一种明显的人更多的用于前端编程,但我现在堆叠。

回答

0

这就是我如何使它工作,所以如果你有和我一样的问题并且在这里发布这个Q,那么希望它也能帮助你:)(不确定它是否是正确的方式,但它适用于我)。它被撞击并错过探索。缺失的地段和一重击底:

  1. 包括在<script></script>标记您的自定义脚本的index.html像这样:

    <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中从脚本部分移除你的库(或者不要包含它)。这不是必需的。