Home > Enterprise >  Use javaScript library with namespaces in angular application
Use javaScript library with namespaces in angular application

Time:09-14

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.

CodePudding user response:

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');
  • Related