![Creative The name of the picture]()

Clash Royale CLAN TAG#URR8PPP
Angular - Failing to intercept http requests using a http service
I have an angular 6 application.
I am assigning a HTTP interceptor to a specific lazy loaded module. When i make http calls directly in the component using http client, the requests are intercepted. However, making http calls via a core module service, it will fail to intercept these http requests.
See the following example.
https://stackblitz.com/edit/angular-ckzdvx?file=src%2Fapp%2Fa%2Ffirst%2Ffirst.component.ts
first.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ApiService } from './../../core/api.service';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
constructor(private http: HttpClient, private apiService: ApiService) { }
ngOnInit() {
}
call() {
this.http.get("https://jsonplaceholder.typicode.com/users").subscribe((res) => {
console.log(res);
})
}
call2() {
this.apiService.get("https://jsonplaceholder.typicode.com/users").subscribe((res) => {
console.log(res);
});
}
}
I am making 2 calls, the first call() is intercepted, the second call2() is not being intercepted.
call()
call2()
Outcome
call2() should be intercepted whilst using the api service.
call2()
It's important that the http interceptor is declared only in the module it is needed in. As i don't want other modules to have their HTTP requests intercepted.
2 Answers
2
I think you need to add the following provider to your app.module.ts to hit all requests
app.module.ts
import { HttpClientModule, HTTP_INTERCEPTORS } from
'@angular/common/http';
import { MyInterceptor} from './my.interceptor';
@NgModule({
imports: [BrowserModule, FormsModule, AppRoutingModule,
CoreModule.forRoot(),
HttpClientModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true
}
})
export class AppModule { }
The reason call2() is not hitting your interceptor is: it is not using FirstComponent's injected HttpClient. It is using ApiService instead. That instance of ApiService has its own HttpClient injected in the constructor and that HttpClient doesn't provide MyInterceptor as an HTTP_INTERCEPTOR.
call2()
FirstComponent
HttpClient
ApiService
ApiService
HttpClient
HttpClient
MyInterceptor
HTTP_INTERCEPTOR
Changing that second call to this.http.get will make it hit your interceptor.
this.http.get
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
probaly apiservice is using different HTTPclient without interceptors.
– Antoniossss
29 mins ago