Member-only story
Should I use the Angular inject function? π
4 min readNov 22, 2024
One of the powers of Angular is dependency injection.
And in the early days of Angular we used the Typescript constructor
to inject the dependencies we needed.
Letβs say we needed to inject a custom UserService
. We would do that via the constructor.
import { Component } from '@angular/core';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `Hello World`
})
export class AppComponent {
constructor(public userService: UserService) { }
}
But that has recently changed with the introduction of the inject
function.
It can now look like this.
import { Component, inject } from '@angular/core';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `Hello World`
})
export class AppComponent {
const userService = inject(UserService);
}
What exactly is dependency injection in Angular?
Dependency injection as a general principal is common among many different frameworks.
ASP.NET Core would be a popular example.