Back to results for “Dependency Injection”
Angular › Services & Dependency Injection

How does the newer inject function differ from using constructor based dependency injection in Angular?

Intermediate

Answer

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.

Common follow-ups: Where exactly can the inject function be called, and where is it not allowed?;Is there any practical difference in behavior between inject and constructor injection inside a component?