I use Angular 9 and i want to add the country name in all requests going to the back end.
I found a blog explaining how to add a request param with interceptor
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
} from "@angular/common/http"
import { Observable } from "rxjs"
export class CountryInterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const cloneReq = req.clone({
params: req.params.set(
"country",
"France"
),
})
return next.handle(cloneReq)
}
}
This is my app.modules
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
NgxShimmerLoadingModule,
SplashScreenModule,
AlertModule.forRoot(),
HttpClientModule,
SimpleNotificationsModule.forRoot(),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
HighlightModule,
LightboxModule,
ClipboardModule,
AppRoutingModule,
InlineSVGModule.forRoot(),
NgbModule,
],
providers: [
CookieService,
{
provide: HIGHLIGHT_OPTIONS,
useValue: {
coreLibraryLoader: () => import('highlight.js/lib/core'),
languages: {
xml: () => import('highlight.js/lib/languages/xml'),
typescript: () => import('highlight.js/lib/languages/typescript'),
scss: () => import('highlight.js/lib/languages/scss'),
json: () => import('highlight.js/lib/languages/json')
},
},
},
IpInterceptorService,
{
provide : APP_INITIALIZER,
useFactory : getIpService,
deps: [IpInterceptorService, HttpClient],
multi : true
},
],
bootstrap: [AppComponent],
})
export class AppModule { }
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http);
}
/**
* Call the service use to get the ip adress of the user, then the country
* @param ipInterceptorService
*/
export function getIpService(ipInterceptorService : IpInterceptorService) {
return ()=> ipInterceptorService.init();
}
But it doesn't work. When i check my request i don't have the country in the params. What did i miss ?
Thanks in advance.