Angular - Understanding Dependency Injection
Angular - Understanding Dependency Injection
mode_edit
Understanding
dependency injection
Dependency injection, or DI, is one of the fundamental concepts in
Angular. DI is wired into the Angular framework and allows classes with
dependency provider.
This topic covers basic scenarios of how a class can act as a dependency.
Angular also allows you to use functions, objects, primitive types such as
string or Boolean, or any other types as dependencies. For more
information, see Dependency providers.
https://angular.io/guide/dependency-injection 1/5
17/07/2023, 15:16 Angular - Understanding dependency injection
Providing dependency
Imagine there is a class called HeroService that needs to act as a
dependency in a component.
The first step is to add the @Injectable decorator to show that the class
can be injected.
@Injectable()
class HeroService {}
@Component({
selector: 'hero-list',
template: '...',
providers: [HeroService]
})
class HeroListComponent {}
When you register a provider at the component level, you get a new
instance of the service with each new instance of that component.
https://angular.io/guide/dependency-injection 2/5
17/07/2023, 15:16 Angular - Understanding dependency injection
Skip @NgModule({
to main content
declarations: [HeroListComponent]
providers: [HeroService]
})
class HeroListModule {}
@Injectable({
providedIn: 'root'
})
class HeroService {}
When you provide the service at the root level, Angular creates a single,
shared instance of the HeroService 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 application if it isn't used, a process known as tree-shaking.
Injecting a dependency
The most common way to inject a dependency is to declare it in a class
https://angular.io/guide/dependency-injection 3/5
17/07/2023, 15:16 Angular - Understanding dependency injection
Skip @Component({
to main content… })
class HeroListComponent {
constructor(private service: HeroService) {}
}
@Component({ … })
class HeroListComponent {
private service = inject(HeroService);
}
the registered provider, and adds it to the injector before returning the
service to Angular.
When all requested services have been resolved and returned, Angular can
https://angular.io/guide/dependency-injection 4/5
17/07/2023, 15:16 Angular - Understanding dependency injection
What's next
Creating and injecting services
https://angular.io/guide/dependency-injection 5/5