Search code examples
angularangular2-servicesangular-httpangular4-httpclient

Angular 4.2.x interceptor is not being executed


I am using
- Angular 4.2.4

I am trying to intercept the service using below angular code

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from 
'@angular/common/http';
import { Observable } from 'rxjs/Rx';
export class LocalHttpClientInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {
  const username = 'me';
  const password = 'blahblah';
  const authReq = req.clone({headers: req.headers.set('Authorization', 
'Basic ' + btoa(username + ':' + password))});
  return next.handle(authReq);
  }
 }

in module file

import { LocalHttpClientInterceptor } from './local-http-client-
interceptor';
  @NgModule({
   imports: [
   CommonModule,
   FormsModule,
   ReactiveFormsModule,
   MdAutocompleteModule,
   MdInputModule,
   MdIconModule,
   HttpModule,
   MdGridListModule,
   FlexLayoutModule
 ],
 declarations: [ UserSearchComponent, ObjectComponent],
 exports: [UserSearchComponent, ObjectComponent, FlexLayoutModule],
 providers : [{
 provide: HTTP_INTERCEPTORS,
 useClass: LocalHttpClientInterceptor,
 multi: true,
 }, UserSearchService, LocalHttpClientService, StorageService]
})
 export class SharedModule { }

Problem : I am able to see that debug point at intercept function definition is triggered, but after doing some service call code inside intercept is not being called.

I am using angular http from @angular/http to call service using get,options,post methods


Solution

  • According to official change logs the package @angular/common/http is available from angular 4.3.0 and you are using 4.2.4 I think that might be the reason. And try to use @angular/common/http instead of @angular/http.

    For how to use new httpClient in angular https://angular.io/guide/http

    Here is the working plunker https://plnkr.co/edit/wtl8EIaCpov6ScwBfPWX?p=preview

    For more change logs visit https://github.com/angular/angular/blob/master/CHANGELOG.md