What is injection through the constructor (constructor injection)?
Constructor injection is a way for Angular to pass dependencies directly into a class's constructor.
When a component or service is created, Angular looks at what its constructor declares and automatically supplies the needed objects from the injector.
Example:
ts
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-profile',
template: `{{ userService.userName }}`
})
export class ProfileComponent {
constructor(public userService: UserService) {}
}Here:
- Angular sees that the constructor needs
UserService; - finds it in the injector;
- creates it (if needed) and supplies it as
userService.
Advantages:
- dependencies are visible right away, from the constructor's signature;
- easy to test, a fake service can be substituted;
- there is no need to create objects manually.
Summary: Constructor injection is the primary way to inject dependencies in Angular: everything a class needs arrives automatically through the constructor's parameters.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.