Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global js variable in angular2 component

I have a global js variable defined below (@Url is an ASP.Net MVC html helper it will get converted to a string value):

<script>
  var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
  System.import('app').catch(function(err){ console.error(err); });
</script>

How do I access rootVar in an angular2 component? I used to use the window service in angular 1.5, is there an analogous way of doing that in angular2?

Specifically, I want to use that rootVar variable to help generate the templateUrl in this component:

import { Component, Inject} from '@angular/core';

@Component({
    selector: 'home-comp',
    templateUrl: '../Home/Root'
})

export class HomeComponent {   
    constructor( ) {  }
}
like image 664
cobolstinks Avatar asked Jun 06 '16 16:06

cobolstinks


People also ask

Is there any global variable in angular?

We always need to declare global variable file for our angular 10 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.

How do I use a global variable in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.


3 Answers

Within your component you could reference window to access the global variables like so:

rootVar = window["rootVar"];

or

let rootVar = window["rootVar"];
like image 180
Riyaz Sayyad Avatar answered Oct 12 '22 22:10

Riyaz Sayyad


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 ) {  }
}
like image 13
Thierry Templier Avatar answered Oct 12 '22 21:10

Thierry Templier


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;
  }
}
like image 10
Dmitriy Avatar answered Oct 12 '22 21:10

Dmitriy