Angular Standalone : provideHttpClient()

By Arvind Rai, January 27, 2024
On this page, we will learn to provide HttpClient for injection in our Angular standalone application. We inject HttpClient in components or services to perform HTTP operations. In Angular standalone application, we need to provide HttpClient for dependency injection using provideHttpClient(). It provides HttpClient with default configurations. To add other configurations, we can pass feature functions to provideHttpClient().
Import provideHttpClient() from @angular/common/http.
import { provideHttpClient } from '@angular/common/http'; 
Here I will discuss using provideHttpClient() in detail.

provideHttpClient()

provideHttpClient() configures HttpClient to be available for injection.
Find the function signature from Angular doc.
provideHttpClient(...features: HttpFeature<HttpFeatureKind>[]): EnvironmentProviders 
Find the code to configure provideHttpClient() to provide HttpClient globally.
app.config.ts
export const APP_CONFIG: ApplicationConfig = {
  providers: [
    provideHttpClient()
  ]
}; 
src/main.ts
bootstrapApplication(AppComponent, APP_CONFIG)
  .catch((err) => console.error(err)); 
By default, provideHttpClient() configures HttpClient with its default options for XSRF protection of outgoing requests. For other configuration options, we need to pass feature functions to provideHttpClient(). Feature functions are created by implementing HttpFeature.
Find the feature functions applied to HttpClient provided by Angular.
withInterceptors : Adds functional style HTTP interceptors.
withInterceptorsFromDi : Adds class based HTTP interceptors.
withXsrfConfiguration : Adds XSRF protection customizations.
withNoXsrfProtection : Disable XSRF protection.
withJsonpSupport : Adds JSONP support.
withRequestsMadeViaParent : Enable current HttpClient instance to make requests via the parent injector's HttpClient.
withFetch : Enables to make requests using the fetch API.

Features functions are used with provideHttpClient() as below.
providers: [
  provideHttpClient(withInterceptors(), withFetch())
] 
We can pass as many features as we want.

Using withInterceptorsFromDi()

Here we will learn to use class based HTTP interceptors with HttpClient.
Suppose we have a class based interceptor.
req-logging-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RequestLoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      tap({
        next: event => {
          if (event instanceof HttpResponse) {
            console.log("Request succeeded: ")
          }
        },
        error: () => console.log("Request failed")
      })
    );
  }
} 
Our service class is injecting HttpClient to perform HTTP operations.
book.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Book } from '../book';

@Injectable({
    providedIn: 'root'
})
export class BookService {
    constructor(private http: HttpClient) { }
    
    findBookByTitle(query: string): Observable<Book[]> {
        const httpParams = new HttpParams().set('name', query);
        return this.http.get<Book[]>("/api/getBook", {
            params: httpParams
        });
    }
}
To enable working of interceptors and HTTP operations, we need to configure provideHttpClient() with withInterceptorsFromDi() as below.
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';

export const APP_CONFIG: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptorsFromDi()),
    [
      { provide: HTTP_INTERCEPTORS, useClass: RequestLoggingInterceptor, multi: true }
    ]
  ]
}; 

Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us