How to access global js variable in angular2 component
Within your component you could reference window to access the global variables like so:
rootVar = window["rootVar"];
or
let rootVar = window["rootVar"];
You need to update the file that bootstraps your application to export a function:
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(rootVar) {
bootstrap(AppComponent, [
provide('rootVar', { useValue: rootVar })
]);
}
Now you can provide the variable from the index.html
file this way:
<script>
var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
System.import('app/main').then((module) => {
module.main(rootVar);
});
</script>
Then you can inject the rootVar
into components and services this way:
import { Component, Inject} from '@angular/core';
@Component({
selector: 'home-comp',
templateUrl: '../Home/Root'
})
export class HomeComponent {
constructor(@Inject('rootVar') rootVar:string ) { }
}