Loading episodes…
0:00 0:00

Angular 16 Inject HttpClient

00:00
BACK TO HOME

Angular 16 Inject HttpClient

10xTeam September 07, 2023 2 min read

There has been an alternate option to inject dependencies in our Angular apps since Angular 14+.

I’ll show you an example of how to utilize the inject function with Angular 16 to inject HttpClient.

Inject Dependencies into Functions (Inject HttpClient Example)

We can now use inject to construct functions and inject dependencies without having to provide arguments to the function class.

For instance, suppose we write a function that requires the HttpClient to obtain data.

import {lastValueFrom, map} from "rxjs";
import {inject} from "@angular/core";
import {HttpClient} from "@angular/common/http";

export function getData(): Promise<unknown> {
  return lastValueFrom(inject(HttpClient).get('YOUR_API_URL').pipe(
    map((response: any) => {
      return response.data;
    })
  ))
}

We can use the function in another class in the constructor lifecycle as follows:

  constructor() {
    getData().then(d => {
      this.data = data;
    })
  }

Please note that the inject() function must be called from an injection context such as a constructor, or a factory function.


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?