Angular 14 inject

Angular 14 inject

We can use the inject() method in components, directives, and pipes thanks to the latest news Angular 14 features. It offers up an entirely new realm of possibilities. We can develop reusable functions that takes advantages of the Angular's dependency injection system.

Read more about the Angular 14 inject feature.

Angular' inject function

Using Angular's inject() function, we can get a reference to a token from the injector that is active. However, only services and factory providers might be called in.

Angular 14 inject capabilities

Angular 14 allows us to call the inject function from inside components, directives, and pipes. This opens the door to an entirely new set of options and possibilities. Using Angular's dependency injection, we can create functions that can be reused.

The inject() function in Angular 14 will radically change how we utilize services. We could do a lot of different things with it.

Here's an example of how we can transform HttpClient.get into a method that may be used anywhere. A constructor is no longer required for a simple get request:

import { inject } from '@angular/core';
import { HttpClient } from '@angular/http/client';

function getUrl(url: string) {
  return inject(HttpClient).get(url);
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  standalone: true,
  styleUrls: ['./app.component.scss']
})
export class AppComponent{
  data$ = getUrl('<url>');
}

  • Date: