Angular ProvidedIn Usage
26-09-2021What is Injectable decorator?
Marks a class as available to Injector for creation.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class UserService { }
The service itself is a class that the CLI generated and that's decorated with @Injectable().
What exactly does providedIn do?
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in the 'root' injector, which will be the application-level injector in most apps.
providedIn: Type<any> | 'root' | null
providedIn: 'root'
When you provide the service at the root level, Angular creates a single, shared instance of service and injects it into any class that asks for it. Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used.
providedIn: Module
It's also possible to specify that a service should be provided in a particular @NgModule. For example, if you don't want a service to be available to applications unless they import a module you've created, you can specify that the service should be provided in the module
import { Injectable } from '@angular/core';
import { UserModule } from './user.module';
@Injectable({ providedIn: UserModule, }) export class UserService { }
This method is preferred because it enables Tree-shaking (Tree shaking is a step in a build process that removes unused code from a code base) 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:
import { NgModule } from '@angular/core'; import { UserService } from './user.service'; @NgModule({ providers: [UserService], }) export class UserModule { }