inject()
Retrieves a dependency from the current injector without constructor params.
Syntax
inject<T>(token: ProviderToken<T>, options?): T Parameters
| Name | Type | Required | Description |
|---|---|---|---|
token | ProviderToken<T> | No | The class or InjectionToken to resolve. |
options | object | No | Supports optional, self, skipSelf, host. |
Returns
T — The resolved dependency instance.
Throws
NullInjectorError— When no provider is found and optional is not set.
Examples
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-data', standalone: true, template: '' })
export class DataComponent {
private http = inject(HttpClient);
load() {
return this.http.get('/api/items');
}
}
Notes
Call inject() within an injection context: constructors, field initializers,
or factory functions. It is the preferred modern alternative to constructor
injection and works well with inheritance and functional guards/resolvers.
Pass `{ optional: true }` to allow a null result.