I have an Interceptor for http get/post requests. It works very well.
Unfortunately it does not work for my jsonp requests / they are not caught.
Therefore I wanted to create another Interceptor that implements JsonpInterceptor.
In fact, it does not work either.
What I've done so far:
AppModule:
[{ provide: HTTP_INTERCEPTORS, useClass: MyJsonpInterceptor, multi: true }],
MyJsonpInterceptor:
@Injectable()
export class MyJsonpInterceptor implements JsonpInterceptor {
constructor(jsonp: JsonpClientBackend) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercept");
}
}
Does someone know, how to intercept jsonp requests in angular 4/5 with the new httpclient?
You have to import the JSONP intercepting module before the HttpClientJsonpModule
import { NgModule, Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {
HttpClient,
HTTP_INTERCEPTORS,
HttpEvent,
HttpRequest,
HttpHandler,
HttpClientModule,
HttpClientJsonpModule
} from '@angular/common/http'
import { Observable } from 'rxjs'
import { AppComponent } from './app.component';
@Injectable()
export class CustomInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: CustomInterceptor, multi: true}
]
})
export class JsonpInterceptingModule {}
@NgModule({
imports: [
BrowserModule,
JsonpInterceptingModule, // Must be before the HttpClientJsonpModule
HttpClientModule,
HttpClientJsonpModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: [
{ provide: HTTP_INTERCEPTORS, multi: true, useClass: CustomInterceptor }
]
})
export class AppModule {
constructor(http: HttpClient){
http.jsonp('https://archive.org/index.php?output=json', 'callback')
.subscribe(response => console.log(response));
}
}
I think JsonpInterceptor
in angular maybe is the key point. Here is my solution:
NgModule
config, Remove HttpClientJsonpModule
.JsonpClientBackend
and {provide: ɵb, useFactory: ɵc}
to providers.ɵb & ɵc are alias for JsonpCallbackContext
and jsonpCallbackContext
{provide: HTTP_INTERCEPTORS, useClass: JsonpInterceptor, multi: true},
as the last HTTP_INTERCEPTORS. Or you can use your custom interceptor overwriting JsonpInterceptor.Hope this can help you.
Update on 2018.03.09:
You can simply do this:
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: XxxInterceptor, multi: true },
],
})
export class XxxModule {
}
@NgModule({
declarations: [
],
imports: [
XxxModule,
HttpClientJsonpModule,
],
providers: [
...
],
bootstrap: [AppComponent]
})
export class AppModule { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With