Angular › Services & Dependency Injection
How does the newer inject function differ from using constructor based dependency injection in Angular?
IntermediateAnswer
The inject function lets you request a dependency directly inside a property initializer or a function, rather than only inside a constructor, which can make code more concise, especially for standalone functions like route guards and resolvers that do not have a class constructor to use.
import { inject } from '@angular/core';
export class UserListComponent {
private userService = inject(UserService);
ngOnInit() {
this.userService.getUsers().subscribe((users) => this.users = users);
}
}Real-world example A route guard function, which has no constructor of its own, uses the inject function to access the AuthService directly, something that would not have been possible using only traditional constructor based injection.