How do you make jsonp calls via the new Angular HttpClientModule?
I see there's an HttpClient.jsonp method but setting up a HttpClientJsonpModule interceptor isn't very clear to me from the documentation. I'm not sure where JsonpCallbackContext should come from?
https://angular.io/api/common/http/HttpClientJsonpModule
EDIT: Just adding HttpClientJsonpModule leads to the following error -
Refused to execute script because its MIME type ('application/json') is not executable
In order to get JSONP to work in Angular (v4.3+) you need to add this to your AppModule
import { HttpClientJsonpModule } from '@angular/common/http';
@NgModule({
imports: [ BrowserModule, HttpClientJsonpModule ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Then in your service or component
private WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php';
const url = searchUrl(term, this.WIKIPEDIA_URL);
this.http.jsonp(url, 'callback')
function searchUrl(term, base) {
let params = new HttpParams()
.append('action', 'opensearch')
.append('search', encodeURIComponent(term))
.append('format', 'json');
return `${base}?${params.toString()}`;
}
Added some params as needed for Wikipedia search to work.
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