3

I have used httpintercept for handling 401 (Unauthorized) error in data services in in my angular 6 project.But httpintercept service not taking in my project.

This is my intercept.services.ts file

export class InterceptService  implements HttpInterceptor {

  constructor(private authService: AuthService) { }

  // intercept request and add token
    intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

      // modify request
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${JSON.parse(localStorage.getItem('currentUser')).token}`
        }
      });

       console.log("----request----");

     console.log(request);

     console.log("--- end of request---");


      return next.handle(request)
      .pipe(
          tap(event => {
            if (event instanceof HttpResponse) {

              console.log(" all looks good");
              // http response status code
              console.log(event.status);
            }
          }, error => {
           // http response status code
              console.log("----response----");
              console.error("status code:");
              console.error(error.status);
              console.error(error.message);
              console.log("--- end of response---");

          })
        )

    };


}

This is my common service.ts page

 import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    import {Http, Response,Headers ,RequestOptions } from "@angular/http";
    import { HttpModule} from '@angular/http';
    import { map } from 'rxjs/operators';
    import { Router } from '@angular/router';

     const API_URL   =  '//api path';



    @Injectable({
        providedIn: 'root'
    })
    export class DataService {
        ctrURL:any;
        postData:any;
        ajaxdata:any;

        constructor(private http:Http,private router: Router) { }
        get_data(url,auth=true){
            //......url : url path......
            //....auth : true api auth required,false no api required....
            var get_url = API_URL + url;
            var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            headers.append('Accept', 'application/json');
            if(auth==true){
                var localStore =    JSON.parse(localStorage.getItem('currentUser'));
                headers.append("Authorization", "Bearer " + localStore.token);
            }
            let options = new RequestOptions({ headers });
            return this.http.get(get_url, options) .pipe((map(res => res.json())));
        }


    }
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
Sandeep Nambiar
  • 1,656
  • 3
  • 22
  • 38

1 Answers1

11

For Angular 4.3+ and above you must use HttpClient instead of Http.

Interceptors work with HttpClient and not Http.

So use below import instead:

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

And in constructor:

constructor(private http:HttpClient,private router: Router) { }

Refer this answer for more on Http and HttpClient.

User3250
  • 2,961
  • 5
  • 29
  • 61