question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Http interceptor not working

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11

github_iconTop GitHub Comments

2reactions
jakehockey10commented, Jan 3, 2020

@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!

1reaction
neikxdcommented, Oct 26, 2021

Just my solution for one who may need:

I worked around with a filter within the HttpInterceptor

  • request.url contains ‘/assets/i18n/’ → ngx-translate TranslateLoader request
  • else others/our request
import { Injectable } from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import {Observable, EMPTY} from 'rxjs';
import {AuthService} from "../services/auth.service";
import {TokenService} from "../services/token.service";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private accountService: AuthService, private tokenService: TokenService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url.includes('/assets/i18n/')) {
      //other request
      let authRequest = request;
      if (!request.url.includes(environment.apiUrl + '/login')) {
        let jwtToken = this.tokenService.getToken();
        if (jwtToken === null) {
          this.accountService.login();
          return EMPTY;
        }
        authRequest = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + jwtToken)});
      }
      return next.handle(authRequest)
    } else {
      //ngx-translate TranslateLoader request
      return next.handle(request)
    }
  }
}

Please report if it works for you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Interceptor not intercepting http requests (Angular 6)
In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule multiple times, for different ...
Read more >
That's why your Angular Interceptor may NOT WORK! [5 ...
EDIT: This problem does not occur when you import HttpClientModule only ONCE in the AppModule or CoreModule (and import the CoreModule into ...
Read more >
Angular: When HttpInterceptor doesn't work with lazy loaded ...
Abou Kone dives into a specific case when using an app wide HttpInterceptor does not work with lazy loaded features.
Read more >
Angular - handle HTTP errors using interceptors
An error interceptor is a special type of interceptor which is used for handling errors that arise while making an HTTP request.
Read more >
Interceptor in component not working? : r/angular - Reddit
In the course he is using BrowserXhr, but its deprecated now. So I created a HttpInterceptor. The problem when I add it on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found