loading...

Provide simple value for components in Angular

danielpdev profile image danielpdev ・1 min read

Sometimes you need to inject a simple value into multiple components

Edit provide-use-value

To inject a simple value you have to pass an object to the providers array of your NgModule decorator.

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: "language",
      useValue: "en"
    }
  ],
  bootstrap: [AppComponent]
})

And in your components import Inject decorator:
@Inject() is a decorator relevant for DI and helps you manually inject a value into your components.

import { Component, Inject } from "@angular/core";

....
export class AppComponent {
  constructor(@Inject("language") private language) {
    console.log(this.language);
  }
}

You can also use @Inject() decorator to provide services from your module.

Ex:

import { Component, Inject } from "@angular/core";
import { AppService } from "./app.service";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(
    @Inject("language") private language,
    @Inject(AppService) private appSer,
    private appSer2: AppService
  ) {
    console.log(this.language, this.appSer, this.appSer2);
  }
}

Using:

...
    @Inject(AppService) private appSer,
    private appSer2: AppService
...

Above code illustrates 2 ways of injecting a service into your component.

Hope you find it useful and see you on the next post!
Stay safe!

Discussion

pic
Editor guide
Collapse
alleamitrano profile image
~AlleAmiDev~

Hi Daniel! I don't understand. Why would you want to inject services this way when they can be provided in Root and initialised in the constructor?

Collapse
danielpdev profile image
danielpdev Author

@Hi AlleAmiDev sorry, but maybe I wasn't enough clear about it.

You are right, using @Inject() it's not a desired way to inject services into your components, but that was just an example.

You should use @Inject('value') when you need to inject just a specific value and not a whole instance.

For ex:

providers: [
    {
      provide: "language",
      useValue: "en"
    }
  ],

and then in your components:

...
    @Inject("language") private language,
....

Did I answer your question? :-)