Intro to angular interceptors and uses | Akashminds

 

interceptor

Today I am going to show how you can deal with Angular interceptors. Interceptors are an awesome thing which can be easily implemented in angular and can give you more advantages like error handling and adding headers. here I am going to show how angular interceptor works and when to use angular interceptor.

What was the problem without interceptors ?

Without interceptors we could have problems like handling ongoing requests or we can say we didn't have a way to handle request and response at real time.

Why do we need to handle request or response in angular

In some places in the application we need to add some additional headers on some requests or we can say you want to add a loader that shows while a http request runs like when the page loads and we don't want any user to interact to the application before the data shows on the page  so we can apply a loader or show some image on the screen so that it can be more user friendly for end users.
we can use angular interceptor to add headers for jwt token and use angular interceptor  to stop request.

How an interceptor works ? 

Interceptors automatically gets triggered when a http request runs on ongoing application , it can help you handle or make changes before the request hits or at the response you get from the request.
what can an angular interceptor do for us:
  • Use interceptors for error handling
  • Use angular interceptor to cancel request or catch error
  • Use angular interceptor to ignore url
  • Use angular interceptor to add header or set header

Steps to set header with angular interceptor

  1. Create a file name with extension interceptor (header.interceptor.ts).
  2. Import and use injectable decorator from @angular/core
  3. Now create a class and give is a name like HeaderInterceptor and implement HttpInterceptor interface to it.
  4. Now you see intercept function added intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {}
  5. Inside the function we can implement the code to handle request and response like shown in the example
  6. Now import the interceptor into app module's providers to let angular application know about the interceptor
  7. Now things are ready you can make request with variables you set into interceptor and thing will work by default.
  8. Make sure you have imported HttpClientModule into app module to make everything working.
Example
header.interceptor.ts
header.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from '../../services/user/user.service';

@Injectable({
  providedIn: 'root'
})
export class HeaderInterceptor implements HttpInterceptor {

  constructor(private users: UserService) { }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    /********** add authorization header with jwt token if available **********/
    const token = this.users.getUserToken // this is to get access token that you get after login
    if (token) {
      request = request.clone({
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Authorization': token
        })
      });
    }
    return next.handle(request);
  }
}
Finally don't forget to import it in app.module.ts and provider
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { HeaderInterceptor } from './header.interceptor';
import { AppComponent } from './app.component';


@NgModule({
  imports:      [ BrowserModule, HttpClientModule ],
  declarations: [ AppComponent,  ],
  bootstrap:    [ AppComponent ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true }
  ]
})
export class AppModule { }
This is how we can use Angular interceptor to add header with jwt token. we can use angular interceptor to handle error , modify response, get response headers, cancel request etc.
angular-intereptor


Summary 

In this article , we found how we to use angular interceptor and where in angular where to put interceptors, we can use multiple http interceptor in angular at a time and Handling http errors with angular http interceptor is a great approach. here you can track going angular http requests and response of multiple API's simultaneously and show some message to user if it logs any error. This can help you making great user interface.

No comments:

Powered by Blogger.