Angular 16 Inject HttpClient

Angular 16 Inject HttpClient

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.


  • Date: