Providing Dependencies with NgModule in Angular

While it’s interesting to see how an injector is created directly, that isn’t the typical way we’d use injections. Instead, what we’d normally do is

1) use NgModule to register what we’ll inject – these are called providers
2) use decorators (generally on a constructor) to specify what we’re injecting

By doing these two steps Angular will manage creating the injector and resolving the dependencies. Let’s convert our UserService to be injectable as a singleton across our app. First, we’re going to add it to the providers key of our NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// imported here
import { UserService } from '../services/user.service';
@NgModule({
imports: [
CommonModule
],
providers: [
UserService // <-- added right here
],
declarations: []
})
export class UserDemoModule { }

Now we can inject UserService into our component like this:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-user-demo',
templateUrl: './user-demo.component.html',
styleUrls: ['./user-demo.component.css']
})
export class UserDemoComponent {
userName: string;
// removed `userService` because of constructor shorthand below
// Angular will inject the singleton instance of `UserService` here.
// We set it as a property with `private`.
constructor(private userService: UserService) {
// empty because we don't have to do anything else!
}
// below is the same...
signIn(): void {
// when we sign in, set the user
// this mimics filling out a login form
this.userService.setUser({
name: 'Nate Murray'
});
// now **read** the user name from the service
this.userName = this.userService.getUser().name;
console.log('User name is: ', this.userName);
}
}

Notice in the constructor above that we have made userService: UserService an argument to the UserDemoComponent. When this component is created on our page Angular will resolve and inject the UserService singleton. What’s great about this is that because Angular is managing the instance, we don’t have to worry about doing it ourselves. Every class that injects the UserService will receive the same singleton.


Providers are the Key

It’s important to know that when we put the UserService on the constructor of the UserDemoComponent, Angular knows what to inject (and how) **because we listed UserService in the providers key of our NgModule.
It does not inject arbitrary classes. You must configure an NgModule for DI to work. We’ve been talking a lot about Singleton services, but we can inject things in lots of other ways.

For any query regarding Providing Dependencies with NgModule in Angular, drop a comment below.

Leave a Comment

Your email address will not be published. Required fields are marked *