inject() vs @Inject() in Angular

·

2 min read

In Angular, inject() and @Inject() are both used for dependency injection but serve slightly different purposes and are used in different contexts. Here's the breakdown:

---

1. inject()

Introduced in Angular 14.

A function-based API for injecting dependencies in classes or standalone functions.

It works only within constructors or top-level execution contexts, like factory providers, functions, or class constructors in Angular.

Use case: Useful when you don’t have access to a constructor (e.g., in a standalone function, signals, or class fields outside constructors).

Example of inject():

import { inject } from '@angular/core';

import { MyService } from './my-service';

const myService = inject(MyService); // Injecting MyService

myService.doSomething();

In components:

import { Component, inject } from '@angular/core';

import { MyService } from './my-service';

@Component({

selector: 'app-example',

template: `<p>Example works!</p>`,

})

export class ExampleComponent {

private myService = inject(MyService); // Injecting MyService

}

Key Points:

inject() works only when a dependency injection context is available (e.g., during Angular bootstrapping).

Cannot be used outside an injection context (like global functions).

---

2. @Inject()

A decorator that is part of Angular's dependency injection system.

Used to explicitly specify a dependency token when injecting a service.

It is typically used when the token cannot be inferred automatically (e.g., when using an interface, a string-based token, or custom providers).

Works in constructor parameters.

Example of @Inject():

import { Inject } from '@angular/core';

import { MY_TOKEN } from './my-token';

constructor(@Inject(MY_TOKEN) private myService: MyService) {

this.myService.doSomething();

}

Here, MY_TOKEN is a custom token (often created with InjectionToken) to explicitly identify what should be injected.

---

Key Differences:

---

When to Use Which?

Use inject() when working outside constructor parameters or in standalone Angular applications where you need dependency injection in a function or class fields.

Use @Inject() when you explicitly need to inject a dependency using a token (like interfaces, strings, or InjectionToken).

Both are part of Angular's p

owerful dependency injection system, but they cater to slightly different use cases.