A provider is an instruction to the DI system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide.
Providing a service
If you already have a CLI generated app, create a service using the following CLI command in the root project directory. Replace User with the name of your service.
ng generate service User
This command creates the following UserService skeleton:
src/app/user.service.0.ts
import { Injectable } from ‘@angular/core’;
@Injectable({
providedIn: ‘root’,
})
export class UserService {
}
You can now inject UserService anywhere in your application.
The service itself is a class that the CLI generated and that’s decorated with @Injectable. By default, this decorator is configured with a providedIn property, which creates a provider for the service. In this case, providedIn: ‘root’ specifies that the service should be provided in the root injector.
Provider scope
When you add a service provider to the root application injector, itโs available throughout the app. Additionally, these providers are also available to all the classes in the app as long they have the lookup token.
You should always provide your service in the root injector unless there is a case where you want the service to be available only if the consumer imports a particular @NgModule.
providedIn and NgModules
It’s also possible to specify that a service should be provided in a particular @NgModule. For example, if you don’t want UserService to be available to applications unless they import a UserModule you’ve created, you can specify that the service should be provided in the module:
src/app/user.service.1.ts
import { Injectable } from ‘@angular/core’;
import { UserModule } from ‘./user.module’;
@Injectable({
providedIn: UserModule,
})
export class UserService {
}
The example above shows the preferred way to provide a service in a module. This method is preferred because it enables tree-shaking of the service if nothing injects it. If it’s not possible to specify in the service which module should provide it, you can also declare a provider for the service within the module:
src/app/user.module.ts
import { NgModule } from ‘@angular/core’;
import { UserService } from ‘./user.service’;
@NgModule({
providers: [UserService],
})
export class UserModule {
}