简体   繁体   中英

Loading javascript global variables in angular 4 typescript source

I'm trying to include "parameters.js" file into my angular 4 project.

You can see below my "parameter.js" file content :

window.myKey = "http://webserviceUrl/"

I want to include this file in my project and get "myKey" value in a typescript file before loading web service datas. My "parameters.js" file as a specific structure and do not be changed (no json :'( ).

Is anyone as loading js into typescript with angular 4 ? How can i do that ?

Thanks for your help.

Include the script in index.html

<script src="/assets/parameters.js" />

And declare the variable in the component where you need to access it

declare let myKey: string;

According to David explainations, i have added my parameters script in my angular conf ".angular-cli.json" like this :

"scripts": [
    "../directory/parameters.js"
],

I can read the value in typescript with the code :

declare let myKey: string;

Thank you David for you great response ! :)

You can Import js locally to ts file like this : import '../../../scripts/custom.js';

then declare method name in custom.js that you want to use like this 👍 declare var fAlert; (declarations statements are usually put just after the import statements) then in a place like ngOnInit directly use this method

fAlert();

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