Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : How declare variable at Module and access it from all component?

Tags:

angular

I want to declare variable in my app.module and access it from children components
without declare it again or use global injection.

Is this possible?

like image 275
Albaz Avatar asked Mar 05 '18 06:03

Albaz


1 Answers

You can define a String Token and inject it at your component via Injector from @angular/core.

App.module.ts

const testVar = 'some value';
@NgModule({
  ...
  providers: [
    { provide: 'A', useValue: testVar}   // define a string token
  ]
})
export class AppModule { }

Component

import { Injector } from '@angular/core';

constructor(private injector: Injector) {
  const A = this.injector.get('A');
  console.log(A);
}

DEMO

like image 121
Pengyy Avatar answered Nov 19 '22 09:11

Pengyy