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.
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
Angular 16 Signals - mutate & update examples Node.js v20.6.0: Introducing Built-in .env File Support Angular 16 Get Routing Parameters with @Input Angular 16 Required Input with Example Angular 16 provideRouter Example: Use Standalone Components with Angular 16 Router Add Jest Support to Angular 16 Angular 16 Inject HttpClient Angular 16 Get the Current Route Example Converting Signals to Observables in Angular 16 Angular 16 Signals ExplainedHands-on Angular eBook
Subscribe to our Angular newsletter and get our hands-on Angular book for free!
