How To Make Interceptor To Send Authtoken For Api Call In Angular5

Posted By : Shilpa Adlakha | 30-Apr-2018

Http interceptor allows modifying HTTP requests globally.While handling authentication in angular we store the JSON Web Token and send it to every API call to check the user is authenticated or not.

Create an Interceptor

 Now we will create a service to make interceptor it is an  Injectable class

import {Injectable } from '@angular/core';
import {
  HttpRequest,
   HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    request = request.clone({
      setHeaders: {
        Authorization: `this.auth.getToken()`
      }
    });
    return next.handle(request);
  }
}

The interceptor is implemented by using the HttpInterceptor interface.Using interceptors we are change outgoing requests and incoming responses,
As we make the copy of the original request we can set the headers that we want and we get from a call to the getToken method from the AuthService which we store in the local storage.
 next.handle which are used to pass the control to the next interceptor if it exists.

Add the Interceptor to Providers
The interceptor should be added to the HTTP_INTERCEPTORS which is an array. In the existing HTTP_INTERCEPTORS array, we use the new class that we have created. Adding this in the provider's array.

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthTokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

Now when we make an HTTP request, the user’s token would be sent with the help of interceptor automatically.


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

export class AppComponent {
  constructor(public http: HttpClient) {}
  public ping() {
    this.http.get('https://demo.com/api/test')
      .subscribe(
        data => console.log(data),
        error => console.log(error)
      );
  }
}

This request will include an Authorization header .we are using Angular’s new HttpClient from @angular/common/http but not the Http class from @angular/http. If we try to make requests with the traditional Httpclass, the interceptor will not work.

 

Thanks

 

 

 

About Author

Author Image
Shilpa Adlakha

Shilpa is a bright Wordpress Developer, she has good knowledge of HTML, CSS, PHP and Wordpress.

Request for Proposal

Name is required

Comment is required

Sending message..