I have a global js variable defined below (@Url is an ASP.Net MVC html helper it will get converted to a string value):
In HTML template you can use method get
<span>{{getGlobalData('rootVar')}}</span>
And create method in component like:
get getGlobalData() {
// Closure workaround
return function(rootVarName) {
return window[rootVarName];
}
}
Within your component you could reference window to access the global variables like so:
rootVar = window["rootVar"];
or
let rootVar = window["rootVar"];
In the component file, outside component class definition, declare rootVar, and it will become available in the component constructor:
declare var rootVar: any;
then
@Component(...)
export class MyComponent {
private a: any;
constructor() {
this.a = rootVar;
}
}
Here don't forget to wash your hands... Angular is just javascript
//Get something from global
let someStuffFromWindow= (<any>window).somethingOnWindow;
//Set something
(<any>window).somethingOnWindow="Stuff From Angular";
This is bad for some reason.. you should feel bad!
Go ahead and use that find and replace fuction for window.
with (<any>window).
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 ) { }
}
A different approach would be to export your var, for ex:
export var API_ENDPOINT = '@Url.Action("Index","Home",new { Area = ""}, null)';
and then import that in your component
import {API_ENDPOINT }