Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

Angular — inject()

--

Angular’s inject API: It’s like a caffeine shot for your services — instantly injected, no constructor required!

Press enter or click to view image in full size

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…

--

--

M Business Solutions
M Business Solutions

Written by M Business Solutions

M Business Solutions delivers tech insights, industry practices, and the latest updates, empowering businesses with expert blogs and innovative solutions.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.