Categories

Tuesday, December 31, 2024
#919814419350 therichposts@gmail.com
AngularAngular 19

Interceptors in an Angular 19 application

Interceptors in an Angular 19 application

Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to share Interceptors in an Angular 19 application.

Angular 19 came. If you are new then you must check below two links:

Now guys here is the complete code snippet and please follow carefully:

To master Interceptors in an Angular 19 application that uses standalone components, follow these steps:


Understanding the Setup

In a standalone Angular app:

  • You bootstrap the app without a module using bootstrapApplication.
  • You configure providers (like HTTP interceptors) at the application level.

Interceptors remain global services, and standalone components don’t change how interceptors work. The key difference lies in where and how you register them.


Steps to Use HTTP Interceptors with Standalone Components

1. Create an HTTP Interceptor

Generate an interceptor using the CLI:

ng generate interceptor logging

This will create the following file:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Request made to:', req.url);

    return next.handle(req);
  }
}

2. Convert to Functional Interceptor (Optional)

Angular 16+ supports functional interceptors for simplicity. Rewrite the interceptor using HttpInterceptorFn:

import { HttpInterceptorFn } from '@angular/common/http';

export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Request made to:', req.url);
  return next(req);
};

3. Register Interceptors in main.ts

Standalone apps bootstrap with bootstrapApplication. Register HTTP interceptors using provideHttpClient with the withInterceptors method:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { loggingInterceptor } from './app/interceptors/logging.interceptor';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(withInterceptors([loggingInterceptor])),
  ],
});

4. Using Interceptors in a Standalone Component

Interceptors work globally for all HTTP requests in your app. In standalone components, HTTP requests are made the same way as in traditional Angular apps.

Example standalone component making an HTTP request:

import { Component } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-data-fetcher',
  standalone: true,
  template: `
    <h1>Data Fetcher</h1>
    <button (click)="fetchData()">Fetch Data</button>
    <div *ngIf="data">
      <pre>{{ data | json }}</pre>
    </div>
  `,
  imports: [HttpClientModule],
})
export class DataFetcherComponent {
  data!: any;

  constructor(private http: HttpClient) {}

  fetchData(): void {
    this.http.get('https://api.example.com/data').subscribe({
      next: (response) => (this.data = response),
      error: (err) => console.error('Error:', err),
    });
  }
}

With the interceptor registered globally, all HTTP requests made in this component will pass through the loggingInterceptor.


5. Add Multiple Interceptors

You can chain multiple interceptors by adding them in the withInterceptors method in main.ts:

import { authInterceptor } from './app/interceptors/auth.interceptor';
import { loggingInterceptor } from './app/interceptors/logging.interceptor';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(
      withInterceptors([authInterceptor, loggingInterceptor])
    ),
  ],
});

Example: Authentication Interceptor

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('access_token');
  const clonedRequest = req.clone({
    setHeaders: {
      Authorization: `Bearer ${token || ''}`,
    },
  });
  return next(clonedRequest);
};

6. Error Handling in Interceptors

Use RxJS operators like catchError for error handling:

import { HttpInterceptorFn } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error) => {
      console.error('HTTP Error:', error.message);
      return throwError(() => new Error('Intercepted Error: ' + error.message));
    })
  );
};

7. Testing the Setup

To test the interceptors:

  • Ensure HTTP requests are intercepted globally.
  • Test how multiple interceptors affect requests and responses.
  • Check that error handling is triggered correctly.

Full main.ts Example:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { authInterceptor } from './app/interceptors/auth.interceptor';
import { loggingInterceptor } from './app/interceptors/logging.interceptor';
import { errorInterceptor } from './app/interceptors/error.interceptor';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(
      withInterceptors([authInterceptor, loggingInterceptor, errorInterceptor])
    ),
  ],
});

Best Practices

  1. Use Functional Interceptors:
  • Simpler and more aligned with Angular’s direction.
  1. Register Interceptors Once:
  • Avoid duplicate registrations in main.ts.
  1. Test Each Interceptor Individually:
  • Verify individual behavior before combining them.
  1. Order Matters:
  • Interceptors are executed in the order they’re registered.
  1. Keep Interceptors Focused:
  • Single responsibility for each interceptor (e.g., logging, authentication, error handling).

With this setup, you can seamlessly integrate HTTP interceptors into Angular 19 applications with standalone components while keeping your code modular and efficient.

Guys if you will have any kind query then feel free to comment below.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.