6

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?

1
  • 8
    You should use services for that. Commented Mar 5, 2018 at 6:55

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.