How to access global js variable in angular2 component

后端 未结 6 1481
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 10:54

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



        
相关标签:
6条回答
  • 2020-12-03 11:15

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-03 11:18

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

    rootVar = window["rootVar"];
    

    or

    let rootVar = window["rootVar"];
    
    0 讨论(0)
  • 2020-12-03 11:18

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-03 11:18

    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).

    0 讨论(0)
  • 2020-12-03 11:22

    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 ) {  }
    }
    
    0 讨论(0)
  • 2020-12-03 11:30

    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 }
    
    0 讨论(0)
提交回复
热议问题