Core: Http interceptor not working

Created on 8 Apr 2019  路  9Comments  路  Source: ngx-translate/core

Hey,

i dont know if iam doing something wrong but i cant get my http interceptor to work.

I added the translation code into my app module.

App Module:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    Angulartics2Module.forRoot(),
    ImgFallbackModule,
    IonicStorageModule.forRoot(),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: translateHttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [
    MediaCapture,
    IOSFilePicker,
    FileChooser,
    NetworkInterface,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The problem is know that when requesting the translation files it will through the interceptor but for my other http request i doesnt.

Interceptor Code:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { PreferenceService } from '../services/preference.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let authReq = req.clone();
        /*if (req.url.indexOf('config') || req.url.indexOf('login') || req.url.indexOf('register'))
           return next.handle(authReq);*/
        const headers = authReq.headers
            .set('Authorization', 'Bearer ${this.preferenceService.usr.token}');
        authReq = req.clone({ headers });
        return next.handle(authReq);

    }
}

Service code:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Plugins, GeolocationPosition } from '@capacitor/core';

import { PreferenceService } from './preference.service';
import { Address } from '../models/Address';

const { Geolocation } = Plugins;

@Injectable({
    providedIn: 'root'
})
export class LocationService {
    constructor(private httpClient: HttpClient, private preferenceService: PreferenceService) { }

    public async getCurrentLocation(): Promise<GeolocationPosition> {
        return await Geolocation.getCurrentPosition();
    }

    public getAddressFromCoordinates(lat: number, lon: number, zoom: number): Promise<Address> {
        return this.httpClient.get<Address>(this.preferenceService.appConfiguration.service_map_link_reverse
            .replace('{lat}', lat.toString())
            .replace('{lng}', lon.toString())
            .replace('{zoom}', zoom.toString())).toPromise();
    }

    uploadMapSnapshot(mapSnapshot: any): Promise<any> {
        const options = {
            headers: new HttpHeaders({

            })
        };

        const formData = new FormData();
        formData.append('files', mapSnapshot);
        formData.append('path', 'map');
        formData.append('refId', '5a993616b8e66660e8baf45c');
        formData.append('ref', 'user');
        formData.append('source', 'users-permissions');

        return this.httpClient.post<any>(this.preferenceService.appConfiguration.app_endpoint + '/upload', formData, options).toPromise();
    }
}

Maybe someone had the same problem or could help me out

Thanks in advantage

Best regards

Lorenzo

Most helpful comment

@lcatania thanks for looking into it! After investigating my issue further yesterday, I determined that the 3rd party interceptor had a guard clause that allowed it to early exit. This is what was happening. I thought the interceptor wasn't running at all but I was wrong.

Thanks again for spending the time trying to help. Much appreciated!

All 9 comments

I'm experiencing the same issue.
Version 11.0.1

It strangely did work several days ago without having changed anything in the TranslateModule.

I got it work and added the interceptors to the sub module where i make the request call and know it gets injected but i dont know why it overwrites when im using it in the root module.

Ok your comment pointed me to the right direction.
The issue occurred after I started modularising my app. It's not that the interceptors are overwritten in the sub module, but rather they are never defined. This is easily fixed by exporting HttpClientModule in your AppModule and then import into your sub modules (or shared module).

I changed my code but im not sure if im doing it right.

app.module.ts

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    IntroWalkthroughPageModule,
    Angulartics2Module.forRoot(),
    ImgFallbackModule,
    IonicStorageModule.forRoot(),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (translateHttpLoaderFactory),
        deps: [HttpBackend]
      }
    })
  ],
  providers: [
    MediaCapture,
    IOSFilePicker,
    OneSignal,
    FileChooser,
    NetworkInterface,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true,
    },
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  exports: [HttpClientModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

home.page.module:

@NgModule({
  imports: [
    CommonModule,
    IonicModule,
    SharedModule,
    HttpClientModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ])
  ],
  providers: [MediaCaptureService, LocationService, FileSelectorService, DeviceInfoService, ShareService, NotificationService],
  declarations: [HomePage]
})
export class HomePageModule { }

What do you mean by importing the HttpClientModule ?

@lcatania did you figure this out? Is that why you closed it? I'm exporting HttpClientModule where I'm importing it, but my interceptors still don't fire in my feature modules.

@jakehockey10 Hi jake, its been a while. i dont really know what i did. I just through my code to figure out if i could help you. What i can say is my interceptors are firing in my feature modules. I can provide you my app.module ... it looks like that :

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    MbscModule,
    FormsModule,
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    Angulartics2Module.forRoot(),
    ImgFallbackModule,
    IonicStorageModule.forRoot({
      name: 'amc_storage'
    }),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (translateHttpLoaderFactory),
        deps: [HttpBackend]
      }
    })
  ],
  providers: [
    Contacts,
    MediaCapture,
    StatusBar,
    ScreenOrientation,
    OneSignal,
    NetworkInterface,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: NetworkInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true,
    },
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: IonicGestureConfig
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

as you can see i dont export anything.
Maybe just try building an minimal exmaple on stackblitz. Hopefully i could help you

@lcatania thanks for looking into it! After investigating my issue further yesterday, I determined that the 3rd party interceptor had a guard clause that allowed it to early exit. This is what was happening. I thought the interceptor wasn't running at all but I was wrong.

Thanks again for spending the time trying to help. Much appreciated!

How did you fixed it?

There was nothing to fix in my case. If I remember correctly, it was a guard running first that was returning false. The interceptor wasnt being run because the guard wasn't letting me get to that point in the app.

Was this page helpful?
0 / 5 - 0 ratings