Member-only story
Angular — inject()
Angular’s inject API: It’s like a caffeine shot for your services — instantly injected, no constructor required!
The Inject API in Angular is used to manually inject dependencies within your components, services, or other Angular constructs. As of Angular 14, the inject() function can be used as a static alternative to injecting services directly through the constructor. It allows you to inject dependencies without requiring constructor-based injection.
Here’s how you can use the inject() API in Angular:
Why use inject() API?
- It’s useful in scenarios where constructor injection is not ideal, such as when working with factory functions, outside of Angular components, or within a functional setup.
- You can inject services dynamically outside of class constructors.
Basic Usage of the inject() API
You can use the inject() API by importing it from @angular/core and passing the token (usually a class or a string token) you want to inject.
Here’s an example:
import { Injectable, inject } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor() {
console.log('MyService Initialized');
}
getServiceMessage() {
return 'Hello from…










