“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.
In Angular, use JSONP by including HttpClientJsonpModule
in the NgModule
imports. In the following example, the searchHeroes()
method uses a JSONP request to query for heroes whose names contain the search term.
/* GET heroes whose name contains search term */ searchHeroes(term: string): Observable { term = term.trim(); const heroesURL = `${this.heroesURL}?${term}`; return this.http.jsonp(heroesUrl, 'callback').pipe( catchError(this.handleError('searchHeroes', [])) // then handle the error ); }
This request passes the heroesURL
as the first parameter and the callback function name as the second parameter. The response is wrapped in the callback function, which takes the observables returned by the JSONP method and pipes them through to the error handler.
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>
.
getTextFile(filename: string) { // The Observable returned by get() is of type Observable<string> // because a text response was specified. // There's no need to pass a <string> type parameter to get(). return this.http.get(filename, {responseType: 'text'}) .pipe( tap( // Log the result or error { next: (data) => this.log(filename, data), error: (error) => this.logError(filename, error) } ) ); }
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.
download() { this.downloaderService.getTextFile('assets/textfile.txt') .subscribe(results => this.contents = results); }
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/http-make-jsonp-request