Including external (hosted) javascript files in Angular2

I am trying to add an external js file to an Angular2 project by adding an entry to my angular-cli.json file.

I added the file to the [scripts] array as shown below:

"scripts": ["https://as-identitydemo--c.na50.visual.force.com/resource/1495420277000/salesforce_login_widget_js"], 

all the other posts that I read relate to using this format for something locally hosted or installed in node_modules, etc.

How to enable external js library and use it in my project?

0
source share
1 answer

You must import the library into your index.html into the header tag. Secondly, you must make the library visible to your Angular project. That means you need captions. You can either search for https://github.com/DefinitelyTyped for existing types or add types to the typings.d.ts file.

Example:

On your page (outside of an Angular application) you may have a global javascript variable:

 var testVar = 'testvalue'; 

Then in the typings.d.ts file you can make this variable globally accessible by adding

 declare var testVar:string; 

You can then access this variable throughout your Angular project as follows:

 console.log(testVar); 

You can do the same with functions in external libraries.

Here is a Plunk that shows that (without a typed file). Hope this helps.

0
source

Source: https://habr.com/ru/post/1268412/


All Articles