0 day streak
javascript / intermediate
Snippet

Modern Dependency Injection with inject()

The inject() function is a modern alternative to constructor-based injection. It allows for cleaner property initialization and can be used in factory functions or outside the constructor context in supported areas.

snippet.js
javascript
1
2
3
4
5
6
export class UserProfileComponent {
private userService = inject(UserService);
private route = inject(ActivatedRoute);
user$ = this.userService.getUser(this.route.snapshot.params['id']);
}
angular
Breakdown
1
inject(UserService)
Retrieves the UserService instance from the DI container.
2
user$ = ...
Directly initializes an Observable property using the injected service.