angular/aio/content/guide/http-make-jsonp-request.md
Sylvain DEDIEU 9bb1884304 docs: change the file of the provideHttpClient standalone example to match cli generated project (#52806)
The "Providing HttpClient through dependency injection" documentation now shows that in case of a standalone boostraped app, the provideHttpClient is to include in the app.config.ts file.

Also updated the http setup server communication example to align the new doc (adev) with the old one (aio).

PR Close #52806
2024-01-25 21:24:58 +00:00

2.4 KiB

HTTP: Make a JSONP request

“JSON with Padding” (JSONP) is a method to deceive a web browser into carrying out requests with a <script> tag that uses the SRC attribute to make a special API request.

Apps can use the HttpClient to make JSONP requests across domains when a server doesn't support CORS protocol.

Angular JSONP requests return an Observable. Follow the pattern for subscribing to observables and use the RxJS map operator to transform the response before using the async pipe to manage the results.

Enable JSONP by providing the HttpClientJsonpModule in the ApplicationConfig providers array in app.config.ts like this:

In the following example, the searchHeroesJsonp() method uses a JSONP request to query for heroes whose names contain the search term acquired from the user.

This request passes the heroesUrl with the search term as the first parameter and the standard callback function name, callback, as the second parameter.

You may have to map the Observable response from the http.jsonp method to the intended data type as this example does with jsonpResultToHeroes.

Request non-JSON data

Not all APIs return JSON data. In this next example, a DownloaderService method reads a text file from the server and logs the file contents, before returning those contents to the caller as an Observable<string>.

HttpClient.get() returns a string rather than the default JSON because of the responseType option.

The RxJS tap operator lets the code inspect both success and error values passing through the observable without disturbing them.

A download() method in the DownloaderComponent initiates the request by subscribing to the service method.

@reviewed 2023-08-17