简体   繁体   English

访问angular2中的全局变量

[英]Access global variable in angular2

Main.ts 维护

 import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 import { AppModule } from './app.module';
 platformBrowserDynamic().bootstrapModule(AppModule);

app.module.ts app.module.ts

 import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule} from '@angular/http';
import { AppComponent     }  from './app.component';
 //service
import { DataService }  from './shared/data.service';
@NgModule({
   imports:      [ BrowserModule, FormsModule, HttpModule],
   declarations: [ AppComponent   ],                
   providers:    [ DataService], 
   bootstrap:    [ AppComponent ]
  })
 export class AppModule {}

starting point 初始点

  <script>
    var temp = "Prafulla";
    System.import('app').catch(function (err) { console.error(err); });
 </script>  

I want to use temp variable inside angular2 I tried using this link Here but not work I donot understand how and where to write main function my app.module.ts 我想to use temp variable inside angular2我尝试使用此链接在这里但没有用,我不了解如何以及在哪里编写我的app.module.ts主要函数

how to do it? 怎么做?

You have to add your value in the providers of the AppModule: 您必须在AppModule的提供程序中添加值:

@NgModule({
   imports: [ BrowserModule, FormsModule, HttpModule],
   declarations: [ AppComponent ],                
   providers: [
                 DataService,
                 {provide: 'rootVar', useValue: rootVar}
              ], 
   bootstrap: [ AppComponent ]
  })
 export class AppModule {}

Now you should be able to access the value in your components and services: 现在,您应该能够访问组件和服务中的值:

export class MyComponent {
    constructor(@Inject('rootVar') rootVar) {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM