1

I'm working on an Angular app where I use an external JavaScript lib:

 <-- the end of the body element -->
 <div id="webapps-sidepanel"></div>
 <script src="./assets/js/tecportalapps.js"></script>

 <script>
   $select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_username'));
 </script>
</body>

Everything works but now the name of the local storage variable name has changed and I need to take the name of environment which is located in the environment.ts file:

export const environment = {
  production: true,
  *envName*: 'PROD',
};

So I need to use something like this:

 $select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_*envName*'));

Is this possible? Any idea on how I can achieve this is welcome. Maybe I can call the $select from the app.component.ts?

3
  • You mean like localStorage.getItem('TMP_' + environment.envName)? Commented Jul 20, 2020 at 10:54
  • @Lain, yes but if I want to use it like this I get this error: Uncaught ReferenceError: environment is not defined Commented Jul 20, 2020 at 10:57
  • Well, if you want to use it, you will have to define/include it somewhere/somehow Commented Jul 20, 2020 at 10:59

2 Answers 2

3

I think you should add your script from app.component.ts

export class AppComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    this.loadScript();
  }

  public loadScript() {
    /* Create your script */
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.src = './assets/js/tecportalapps.js';

    /* Do your stuff with environement variable or localstorage */
    console.log(environment.envName);
    console.log(localStorage.getItem("envName"));

    /* add your script to DOM */
    body.appendChild(script);
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

It's totally ok to import the script in the index.html as it originally was. The key is to execute the enviroment dependent code in the context of Angular (app.component.ts)
1

In the index.html you are out of the context of Angular yet, so you have no chance of reading the value of your environment file.

Try executing your code in the app.component.ts.

To be able to do this, you have to make typescript recognize $select as an existing function. There are a couple of ways to do this (read more: https://mariusschulz.com/blog/declaring-global-variables-in-typescript)

Example, app.component.ts:

(window as any).$select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_' + environment.envName));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.