Search code examples
angularionic3ionic-native

Http Intercepter Error in ionic 3 + Angular 5+


I am using simple http intercepter class to pass jwt token to server through header. I have written the http intercept class but when i run it shows run time error.. do any one have implement http intercepter in ionic 3 and angular 5+..

please help

here iam attaching app.module.ts

  providers: [
StatusBar,
SplashScreen,
StatusBar,HttpClient,
Push,
{provide: HTTP_INTERCEPTORS,useClass:TokenIntercepterProvider},
{provide: ErrorHandler, useClass: IonicErrorHandler},
StudentDetailsProvider,
EventServiceProvider,
EventServiceProvider,
AttendanceProvider,
GroupChatServiceProvider,
ChatserviceProvider,
RestProvider,
LocationServiceProvider,
GoogleMaps,
NativeGeocoder,
StudentparentinfoProvider,
RestusersProvider,
FcmProvider,
TokenIntercepterProvider

] })

here is tokenIntercepterProvider

import {HttpClient, HttpInterceptor} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {HttpRequest,HttpHandler,HttpEvent} from "@angular/common/http";
import  {Observable} from "rxjs/Observable";
import {Storage} from "@ionic/storage";


@Injectable()
export class TokenIntercepterProvider implements HttpInterceptor{
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const changedReq = req.clone({headers: req.headers.set('Authorization', 'Bearer xxx.xy.yyx')});
    return next.handle(changedReq);

  }

  constructor(private inj:Injector) {
    console.log('Hello TokenIntercepterProvider Provider');
  }

}

here iam hardcode a string to the bearer token even this is not working

the error i get when i run this

error i got

i get following error: Provider parse errors.mixing multi and no multi provider is not possible for token injection token _HTTP_INTERCEPTERS("[ERROR->]"): in NgModule AppModule in ./AppModule@-1:-1


Solution

  • Try this solution :

    Add

    { provide: HTTP_INTERCEPTORS, useClass: TokenIntercepterProvider, multi: true, }

    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    
    providers: [
        StatusBar,
        SplashScreen,
        StatusBar,HttpClient,
        Push,
        {provide: HTTP_INTERCEPTORS,useClass:TokenIntercepterProvider},
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        StudentDetailsProvider,
        EventServiceProvider,
        EventServiceProvider,
        AttendanceProvider,
        GroupChatServiceProvider,
        ChatserviceProvider,
        RestProvider,
        LocationServiceProvider,
        GoogleMaps,
        NativeGeocoder,
        StudentparentinfoProvider,
        RestusersProvider,
        FcmProvider,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: TokenIntercepterProvider,
          multi: true,
        },
        ]