Http interceptor not working
See original GitHub issueHey,
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:
- Created 4 years ago
- Comments:11
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@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!
Just my solution for one who may need:
I worked around with a filter within the HttpInterceptor
Please report if it works for you.