Http Interceptor not working in angular 6

Sandeep Nambiar

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())));
        }


    }
User3250

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Angular 6 Interceptor not working as expected

Authentication Interceptor not working in angular 6

Angular 7 HTTP Interceptor is not working

Angular 6 - Modifying response body in interceptor not working

Http interceptor on response not working in angular 5

Angular 6 HTTP Interceptor not setting headers

Interceptor not intercepting http requests (Angular 6)

Interceptor not intercepting http POST requests (Angular 6)

Login not working after adding HTTP Interceptor - Angular 5

how to change http req url using angular 6 interceptor

Angular 6 - HTTP Interceptor and net :: ERR_TIMED_OUT

Angular 4.3 Interceptor not working

Testing Angular http interceptor

Angular 4 - HTTP Interceptor

Angular 6 http.delete request not working

Angular 6 http not working with single JSON item

Angular Logout Interceptor Not Working Properly

Ionic Angular Auth Interceptor not working

Angular 6 - Interceptor Preflight (CORS)

Angular HTTP interceptor for Authentication header

Angular 6 Http Interceptor only works on request with same port api request

Angular 6: Calling service observer.next from Http Interceptor causes infinite request loop

Angular 4 HTTP request from HTTP interceptor

$httpProvider interceptor not working when $http is injected into a factory

Angular HTTP Interceptor test fails while the interceptor works fine

How to setup interceptor header in Angular 6

Angular 6 - Auth token interceptor not adding headers

ExpressionChangedAfterItHasBeenCheckedError error because of loader interceptor in angular 6

Angular 7 - Global HTTP Interceptor for whole Application