Loading episodes…
0:00 0:00

Angular 14 inject

00:00
BACK TO HOME

Angular 14 inject

ahmed June 14, 2022 2 min read

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>');
}

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?