简体   繁体   中英

Use javaScript library with namespaces in angular application

I have a Javascript library. It contains functions, which are encapsulated in namespaces like this:

var testNamespace = {
    insideFunction: function(str) {
        alert(atr);
    }
};

I need to use these functions inside my Angular app.component.ts file. I was able to connect this JS library to my Angular. If I remove namespaces from JS, declare the function in app.component.ts and try to use it, it works perfectly. This is the example of my working code, when I removed namespaces from JS library:

declare function insideFunction(str: string): void;

...

export class AppComponent {

  public test(str: string): void {
    insideFunction(str);
  }

}

The problem is that I am not allowed to remove namespaces, the functions inside JS file still have to be encapsulated. So, my question is: how do I declare and use external javascript functions, contained in namespaces? I am completely new to frontend-development and would appreciate any help.

You can use this namespace in your angular app, by declaring them. Create a file with the name of typings.d.ts in the src folder of the angular project, then define your namespace like this:

declare namespace testNamespace {
  export function insideFunction(str: string);
}

After that you can use that namespace in any angular component like this:

testNamespace.insideFunction('test');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM