Daniel Grima Daniel Grima - 1 month ago 11
TypeScript Question

Issue with passing global "external" variables to Angular 2 application

I've been setting up a global external object which I can then pass to my Angular application. I'm doing this as the application will be provided to different websites and so each website can then pass different configurations.

This is my setup:

index.html

<script type="text/javascript">
var appConfig = {
welcome_msg: 'Welcome to Test App'
};
</script>


Exporting the appConfig object in the application (
test-export.ts
)

import { OpaqueToken } from '@angular/core';

export let APP_CONFIG = new OpaqueToken('appConfig');


Injecting appConfig in a component

...

import { APP_CONFIG } from '../../app/test-export';

@Component({
selector: `<home></home>`,
providers: [
{ provide: APP_CONFIG, useValue: appConfig }
],
styleUrls: [ './home.style.css' ],
templateUrl: './home.template.html'
})

export class HomeComponent implements OnInit {
constructor(@Inject(APP_CONFIG) private appConfig: any) { }
}


Using value in the template

<h1>{{ appConfig.welcome_msg }}</h1>


All of the above works fine and I get no errors when running the application, however after I build the code I'm getting the following error:

Cannot find name 'appConfig'.


In fact even in Visual Studio Code it's being marked as "incorrect":

enter image description here

I'm using WebPack and when I'm running in "dev mode" I simply get the error when I build but the application runs successfully. However the issue is that when I try to build in "prod mode" the application does not build because of this error.

As references I was following this question on StackOverflow and this article. Am I missing an export, or could it somehow be a configuration issue?

Answer

You need to import the file that contains appConfig. If the script is in index.html this is not possible.

What you can do is to make it global by assigning it to window

<script type="text/javascript">
    window.appConfig = {
        welcome_msg: 'Welcome to Test App'
    };
</script>
providers: [
    { provide: APP_CONFIG, useValue: (<any>window).appConfig }
    // or
    { provide: APP_CONFIG, useValue: (window as any).appConfig }
    // or
    { provide: APP_CONFIG, useValue: window['appConfig'] }
],