How to access global js variable in angular2 component

后端 未结 6 1501
佛祖请我去吃肉
佛祖请我去吃肉 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: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:

    
    

    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 ) {  }
    }
    

提交回复
热议问题