Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular jsonp calls

Tags:

angular

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
like image 635
Daaavvy Avatar asked Oct 15 '25 07:10

Daaavvy


1 Answers

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.

like image 89
Gerard Sans Avatar answered Oct 17 '25 13:10

Gerard Sans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!