user7324396
user7324396

Reputation:

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

 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

how to do it?

Upvotes: 1

Views: 3736

Answers (1)

Dinistro
Dinistro

Reputation: 5730

You have to add your value in the providers of the 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) {}
}

Upvotes: 3

Related Questions