From f06d5f02b33f6ef8e499290c0bf4bf44e09ff0b4 Mon Sep 17 00:00:00 2001 From: Judy Bogart Date: Tue, 3 Mar 2020 13:57:29 -0800 Subject: [PATCH] docs: update http guide (#35859) PR Close #35859 --- aio/content/guide/http.md | 653 ++++++++++++++++++------------------ aio/content/navigation.json | 5 + 2 files changed, 331 insertions(+), 327 deletions(-) diff --git a/aio/content/guide/http.md b/aio/content/guide/http.md index ddebe2969e..47eca7e182 100644 --- a/aio/content/guide/http.md +++ b/aio/content/guide/http.md @@ -1,15 +1,55 @@ # Communicating with backend services using HTTP -Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the `XMLHttpRequest` interface and the `fetch()` API. +Most front-end applications need to communicate with a server over the HTTP protocol, in order to download or upload data and accesss other back-end services. +Angular provides a simplified client HTTP API for Angular applications, the `HttpClient` service class in `@angular/common/http`. -The `HttpClient` in `@angular/common/http` offers a simplified client HTTP API for Angular applications -that rests on the `XMLHttpRequest` interface exposed by browsers. -Additional benefits of `HttpClient` include testability features, typed request and response objects, request and response interception, `Observable` apis, and streamlined error handling. +Modern browsers support two different APIs for making HTTP requests: the `XMLHttpRequest` interface and the `fetch()` API. `HttpClient` is built on the `XMLHttpRequest` interface exposed by browsers. Major features include: -You can run the that accompanies this guide. +* The ability to request [typed response objects](#typed-response). +* Streamlined [error handling](#error-handling). +* [Testability](#testing-requests) features. +* Request and response [interception](#intercepting-requests-and-responses). + +##### Prerequisites + +Before working with the `HTTPClientModule`, you should have a basic understanding of the following: + +* TypeScript programming +* Usage of the HTTP protocol +* Angular app-design fundamentals, as described in [Angular Concepts](guide/architecture) +* Observable techniques and operators. See the [Observables](guide/observables) guide. + +## Setup for server communication + +Before you can use `HttpClient`, you need to import the Angular `HttpClientModule`. +Most apps do so in the root `AppModule`. + + + + +You can then inject the `HttpClient` service as a dependency of an application class, as shown in the following `ConfigService` example. + + + + +The `HttpClient` service makes use of [observables](guide/glossary#observable "Observable definition") for all transactions. You must import the RxJS observable and operator symbols that appear in the example snippets. These `ConfigService` imports are typical. + + +
+You can run the that accompanies this guide. + The sample app does not require a data server. It relies on the [Angular _in-memory-web-api_](https://github.com/angular/in-memory-web-api/blob/master/README.md), @@ -20,30 +60,41 @@ Look at the `AppModule` _imports_ to see how it is configured.
-## Setup +## Requesting data from a server -Before you can use the `HttpClient`, you need to import the Angular `HttpClientModule`. -Most apps do so in the root `AppModule`. +Use the [`HTTPClient.get()`](api/common/http/HttpClient#get) method to fetch data from a server. +The aynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. +The return type varies based on the `observe` and `responseType` values that you pass to the call. - - +The `get()` method takes two arguments; the endpoint URL from which to fetch, and an *options* object that you can use to configure the request. -Having imported `HttpClientModule` into the `AppModule`, you can inject the `HttpClient` -into an application class as shown in the following `ConfigService` example. +``` +options: { + headers?: HttpHeaders | {[header: string]: string | string[]}, + observe?: 'body' | 'events' | 'response', + params?: HttpParams|{[param: string]: string | string[]}, + reportProgress?: boolean, + responseType?: 'arraybuffer'|'blob'|'json'|'text', + withCredentials?: boolean, + } +``` - - +Important options include the *observe* and *responseType* properties. -## Requesting data from server +* The *observe* option specifies how much of the response to return. +* The *responseType* option specifies the format in which to return data. -Applications often request JSON data from the server. -For example, the app might need a configuration file on the server, `config.json`, +
+ +You can use the `options` object to configure various other aspects of an outgoing request. +In [Adding headers](#adding-headers), for example, the service set the default headers using the `headers` option property. + +Use the `params` property to configure a request with [HTTP URL parameters](#url-params), and the `reportProgress` option to [listen for progress events](#report-progress) when transferring large amounts of data. + +
+ +Applications often request JSON data from a server. +In the `ConfigService` example, the app needs a configuration file on the server, `config.json`, that specifies resource URLs. -The `ConfigService` fetches this file with a `get()` method on `HttpClient`. +To fetch this kind of data, the `get()` call needs the following options: `{observe: 'body', responseType: 'json'}`. +These are the default values for those options, so the following examples do not pass the options object. +Later sections show some of the additional option possibilities. + +The example conforms to best practice for creating scalable solutions by defining a re-usable [injectable service](guide/glossary#service "service definition") to perform the data-handling functionality. +In addition to fetching data, the service can post-process the data, add error handling, and add retry logic to cope with intermittent connectivity. + +The `ConfigService` fetches this file using the `HttpClient.get()` method. -A component, such as `ConfigComponent`, injects the `ConfigService` and calls +The `ConfigComponent` injects the `ConfigService` and calls the `getConfig` service method. +Because the service method returns an `Observable` of configuration data, +the component *subscribes* to the method's return value. +The subscription callback performs minimal post-processing. +It copies the data fields into the component's `config` object, which is data-bound in the component template for display. + -Because the service method returns an `Observable` of configuration data, -the component **subscribes** to the method's return value. -The subscription callback copies the data fields into the component's `config` object, -which is data-bound in the component template for display. - -
-
Why write a service?
- -This example is so simple that it is tempting to write the `Http.get()` inside the -component itself and skip the service. -In practice, however, data access rarely stays this simple. -You typically need to post-process the data, add error handling, and maybe some retry logic to -cope with intermittent connectivity. - -The component quickly becomes cluttered with data access minutia. -The component becomes harder to understand, harder to test, and the data access logic can't be re-used or standardized. - -That's why it's a best practice to separate presentation of data from data access by -encapsulating data access in a separate service and delegating to that service in -the component, even in simple cases like this one. -
+{@a typed-response} ### Requesting a typed response You can structure your `HttpClient` request to declare the type of the response object, to make consuming the output easier and more obvious. -Specifying the response type acts as a type assertion during the compile time. +Specifying the response type acts as a type assertion at compile time. + +
+ +Specifying the response type is a declaration to TypeScript that it should expect your response to be of the given type. +This is a build-time check and doesn't guarantee that the server will actually respond with an object of this type. It is up to the server to ensure that the type specified by the server API is returned. + +
To specify the response object type, first define an interface with the required properties. -(Use an interface rather than a class; a response cannot be automatically converted to an instance of a class.) +(Use an interface rather than a class, because you cannot automatically convert the response to an instance of a class.) - When you pass an interface as a type parameter to the `HttpClient.get()` method, use the RxJS `map` operator to transform the response data as needed by the UI. You can then pass the transformed data to the [async pipe](api/common/AsyncPipe). + When you pass an interface as a type parameter to the `HttpClient.get()` method, you can use the [RxJS `map` operator](guide/rx-library#operators) to transform the response data as needed by the UI. You can then pass the transformed data to the [async pipe](api/common/AsyncPipe). @@ -126,36 +176,30 @@ easier and safer to consume: header="app/config/config.component.ts (showConfig v.2)"> -
- -Specifying the response type is a declaration to TypeScript that it should expect your response to be of the given type. -This is a build-time check and doesn't guarantee that the server will actually respond with an object of this type. It is up to the server to ensure that the type specified by the server API is returned. - -
- To access properties that are defined in an interface, you must explicitly convert the Object you get from the JSON to the required response type. For example, the following `subscribe` callback receives `data` as an Object, and then type-casts it in order to access the properties. .subscribe(data => this.config = { - heroesUrl: (data as any).heroesUrl, - textfile: (data as any).textfile, + heroesUrl: (data as any).heroesUrl, + textfile: (data as any).textfile, }); - ### Reading the full response -The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow. +In the previous example, the call to `HttpClient.get()` did not specify any options. By default, it returned the JSON data contained in the response body. -Tell `HttpClient` that you want the full response with the `observe` option: +You might need more information about the transaction than is contained in the response body. Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow. + +Tell `HttpClient` that you want the full response with the `observe` option of the `get()` method: -Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data. +Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data contained in the body. The component's `showConfigResponse()` method displays the response headers as well as the configuration: @@ -170,7 +214,7 @@ As you can see, the response object has a `body` property of the correct type. ### Making a JSONP request -Apps can use the `HttpClient` to make [JSONP](https://en.wikipedia.org/wiki/JSONP) requests across domains when the server doesn't support [CORS protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). +Apps can use the `HttpClient` to make [JSONP](https://en.wikipedia.org/wiki/JSONP) requests across domains when a server doesn't support [CORS protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). 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](api/common/AsyncPipe) to manage the results. @@ -216,38 +260,32 @@ A `download()` method in the `DownloaderComponent` initiates the request by subs header="app/downloader/downloader.component.ts (download)" linenums="false"> -## Error handling +{@a error-handling} -What happens if the request fails on the server, or if a poor network connection prevents it from even reaching the server? `HttpClient` will return an _error_ object instead of a successful response. +## Handling request errors -You _could_ handle in the component by adding a second callback to the `.subscribe()`: +If the request fails on the server, or if a poor network connection prevents it from even reaching the server, `HttpClient` returns an _error_ object instead of a successful response. - - +The same service that performs your server transactions should also perform error inspection, interpretation, and resolution. -It's certainly a good idea to give the user some kind of feedback when data access fails. -But displaying the raw error object returned by `HttpClient` is far from the best way to do it. +When an error occurs, you can obtain details of what failed in order to inform your user. In some cases, you might also automatically [retry the request](#retry). {@a error-details} ### Getting error details -Detecting that an error occurred is one thing. -Interpreting that error and composing a user-friendly response is a bit more involved. +An app should give the user useful feedback when data access fails. +A raw error object is not particularly useful as feedback. +In addition to detecting that an error has occurred, you will need to get error details and use that compose a user-friendly response. -Two types of errors can occur. The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error _responses_. +Two types of errors can occur. -Or something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator. These errors produce JavaScript `ErrorEvent` objects. +* The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error _responses_. -The `HttpClient` captures both kinds of errors in its `HttpErrorResponse` and you can inspect that response to figure out what really happened. +* Something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator. These errors produce JavaScript `ErrorEvent` objects. -Error inspection, interpretation, and resolution is something you want to do in the _service_, -not in the _component_. +`HttpClient` captures both kinds of errors in its `HttpErrorResponse`. You can inspect that response to figure out what really happened. -You might first devise an error handler like this one: +The following example defines an error handler in the previously defined ConfigService. -Notice that this handler returns an RxJS [`ErrorObservable`](#rxjs) with a user-friendly error message. -Consumers of the service expect service methods to return an `Observable` of some kind, -even a "bad" one. - -Now you take the `Observables` returned by the `HttpClient` methods -and _pipe them through_ to the error handler. +The handler returns an RxJS `ErrorObservable` with a user-friendly error message. +The following code updates the `getConfig()` method, using a [pipe](guide/pipes "Pipes guide") to send all observables returned by the `HttpClient.get()` call to the error handler. -### Retrying +{@a retry} +### Retrying a failed request Sometimes the error is transient and will go away automatically if you try again. For example, network interruptions are common in mobile scenarios, and trying again -may produce a successful result. +can produce a successful result. -The [RxJS library](#rxjs) offers several _retry_ operators that are worth exploring. -The simplest is called `retry()` and it automatically re-subscribes to a failed `Observable` a specified number of times. _Re-subscribing_ to the result of an `HttpClient` method call has the effect of reissuing the HTTP request. +The [RxJS library](guide/rx-library) offers several _retry_ operators that are worth exploring. +For example, the `retry()` operator automatically re-subscribes to a failed `Observable` a specified number of times. _Re-subscribing_ to the result of an `HttpClient` method call has the effect of reissuing the HTTP request. -_Pipe_ it onto the `HttpClient` method result just before the error handler. +The following example shows how you can pipe a failed request to the `retry()` operator before handing it on to the error handler. -{@a rxjs} -## Observables and operators -The previous sections of this guide referred to RxJS `Observables` and operators such as `catchError` and `retry`. -You will encounter more RxJS artifacts as you continue below. +## Sending data to a server -[RxJS](http://reactivex.io/rxjs/) is a library for composing asynchronous and callback-based code -in a _functional, reactive style_. -Many Angular APIs, including `HttpClient`, produce and consume RxJS `Observables`. - -RxJS itself is out-of-scope for this guide. You will find many learning resources on the web. -While you can get by with a minimum of RxJS knowledge, you'll want to grow your RxJS skills over time in order to use `HttpClient` effectively. - -If you're following along with these code snippets, note that you must import the RxJS observable and operator symbols that appear in those snippets. These `ConfigService` imports are typical. - - - - -## HTTP headers - -Many servers require extra headers for save operations. -For example, they may require a "Content-Type" header to explicitly declare the MIME type of the request body; or the server may require an authorization token. - -### Adding headers - -The `HeroesService` defines such headers in an `httpOptions` object that will be passed -to every `HttpClient` save method. - - - - -### Updating headers - -You can't directly modify the existing headers within the previous options -object because instances of the `HttpHeaders` class are immutable. - -Use the `set()` method instead, to return a clone of the current instance with the new changes applied. - -Here's how you might update the authorization header (after the old token expired) before making the next request. - - - - -## Sending data to the server - -In addition to fetching data from the server, `HttpClient` supports mutating requests, that is, sending data to the server with other HTTP methods such as PUT, POST, and DELETE. +In addition to fetching data from a server, `HttpClient` supports mutating requests, that is, sending data to a server with other HTTP methods such as PUT, POST, and DELETE. The sample app for this guide includes a simplified version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them. @@ -462,16 +447,71 @@ The following `HeroesService` example is just like the POST example. For the reasons [explained above](#always-subscribe), the caller (`HeroesComponent.update()` in this case) must `subscribe()` to the observable returned from the `HttpClient.put()` in order to initiate the request. -## Advanced usage +### Adding and updating headers -We have discussed the basic HTTP functionality in `@angular/common/http`, but sometimes you need to do more than make simple requests and get data back. +Many servers require extra headers for save operations. +For example, a server might require an authorization token, or "Content-Type" header to explicitly declare the MIME type of the request body. -{@a intercepting-requests-and-responses } -### HTTP interceptors +##### Adding headers + +The `HeroesService` defines such headers in an `httpOptions` object that will be passed +to every `HttpClient` save method. + + + + +##### Updating headers + +You can't directly modify the existing headers within the previous options +object because instances of the `HttpHeaders` class are immutable. +Use the `set()` method instead, to return a clone of the current instance with the new changes applied. + +The following example shows how, when an old token has expired, you can update the authorization header before making the next request. + + + + +{@a url-params} + +## Configuring HTTP URL parameters + +Use the `HttpParams` class with the `params` request option to add URL query strings in your `HttpRequest`. + +The following example, the `searchHeroes()` method queries for heroes whose names contain the search term. +Start by importing `HttpParams` class. + + +import {HttpParams} from "@angular/common/http"; + + + + + +If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. +If the term is "cat", for example, the GET request URL would be `api/heroes?name=cat`. + +The `HttpParams` object is immutable. If you need to update the options, save the returned value of the `.set()` method. + +You can also create HTTP parameters directly from a query string by using the `fromString` variable: + + +const params = new HttpParams({fromString: 'name=foo'}); + + + +{@a intercepting-requests-and-responses} +## Intercepting requests and responses _HTTP Interception_ is a major feature of `@angular/common/http`. -With interception, you declare _interceptors_ that inspect and transform HTTP requests from your application to the server. -The same interceptors may also inspect and transform the server's responses on their way back to the application. +With interception, you declare _interceptors_ that inspect and transform HTTP requests from your application to a server. +The same interceptors may also inspect and transform a server's responses on their way back to the application. Multiple interceptors form a _forward-and-backward_ chain of request/response handlers. Interceptors can perform a variety of _implicit_ tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response. @@ -479,7 +519,7 @@ Interceptors can perform a variety of _implicit_ tasks, from authentication to Without interception, developers would have to implement these tasks _explicitly_ for each `HttpClient` method call. -#### Write an interceptor +### Write an interceptor To implement an interceptor, declare a class that implements the `intercept()` method of the `HttpInterceptor` interface. @@ -500,11 +540,11 @@ export abstract class HttpHandler { } ``` -Like `intercept()`, the `handle()` method transforms an HTTP request into an `Observable` of [`HttpEvents`](#httpevents) which ultimately include the server's response. The `intercept()` method could inspect that observable and alter it before returning it to the caller. +Like `intercept()`, the `handle()` method transforms an HTTP request into an `Observable` of [`HttpEvents`](#interceptor-events) which ultimately include the server's response. The `intercept()` method could inspect that observable and alter it before returning it to the caller. This _no-op_ interceptor simply calls `next.handle()` with the original request and returns the observable without doing a thing. -#### The _next_ object +### The _next_ object The `next` object represents the next interceptor in the chain of interceptors. The final `next` in the chain is the `HttpClient` backend handler that sends the request to the server and receives the server's response. @@ -515,7 +555,7 @@ An interceptor _could_ skip calling `next.handle()`, short-circuit the chain, an This is a common middleware pattern found in frameworks such as Express.js. -#### Provide the interceptor +### Provide the interceptor The `NoopInterceptor` is a service managed by Angular's [dependency injection (DI)](guide/dependency-injection) system. Like other services, you must provide the interceptor class before the app can use it. @@ -570,7 +610,7 @@ There are many more interceptors in the complete sample code. -#### Interceptor order +### Interceptor order Angular applies interceptors in the order that you provide them. If you provide interceptors _A_, then _B_, then _C_, requests will flow in _A->B->C_ and @@ -579,37 +619,41 @@ responses will flow out _C->B->A_. You cannot change the order or remove interceptors later. If you need to enable and disable an interceptor dynamically, you'll have to build that capability into the interceptor itself. -#### _HttpEvents_ +{@a interceptor-events} -You may have expected the `intercept()` and `handle()` methods to return observables of `HttpResponse` as most `HttpClient` methods do. +### Handling interceptor events -Instead they return observables of `HttpEvent`. +While most other `HttpClient` methods return observables of `HttpResponse`, the `intercept()` and `handle()` methods to return observables of `HttpEvent`. -That's because interceptors work at a lower level than those `HttpClient` methods. A single HTTP request can generate multiple _events_, including upload and download progress events. The `HttpResponse` class itself is actually an event, whose type is `HttpEventType.Response`. +The `HttpResponse` class itself is actually an event, whose type is `HttpEventType.Response`. +A single HTTP request can, however, generate multiple events of other types, including upload and download progress events. -Many interceptors are only concerned with the outgoing request and simply return the event stream from `next.handle()` without modifying it. +Many interceptors are only concerned with the outgoing request and return the event stream from `next.handle()` without modifying it. +Some interceptors, however, need to examine and modify the response from `next.handle()`; these operations can see all of these events in the stream. -But interceptors that examine and modify the response from `next.handle()` -will see all of these events. -Your interceptor should return _every event untouched_ unless it has a _compelling reason to do otherwise_. +{@a immutability} -#### Immutability - -Although interceptors are capable of mutating requests and responses, +Although interceptors are capable of modifying requests and responses, the `HttpRequest` and `HttpResponse` instance properties are `readonly`, rendering them largely immutable. - -They are immutable for a good reason: the app may retry a request several times before it succeeds, which means that the interceptor chain may re-process the same request multiple times. +They are immutable for a good reason: an app might retry a request several times before it succeeds, which means that the interceptor chain may re-process the same request multiple times. If an interceptor could modify the original request object, the re-tried operation would start from the modified request rather than the original. Immutability ensures that interceptors see the same request for each try. -TypeScript will prevent you from setting `HttpRequest` readonly properties. +
+ + Your interceptor should return every event without modification unless it has a compelling reason to do otherwise. + +
+ +TypeScript prevents you from setting `HttpRequest` read-only properties. ```javascript // Typescript disallows the following assignment because req.url is readonly req.url = req.url.replace('http://', 'https://'); ``` -To alter the request, clone it first and modify the clone before passing it to `next.handle()`. -You can clone and modify the request in a single step as in this example. + +If you must alter a request, clone it first and modify the clone before passing it to `next.handle()`. +You can clone and modify the request in a single step, as shown in the following example. -##### Clearing the request body +#### Clearing the request body in a clone Sometimes you need to clear the request body rather than replace it. -If you set the cloned request body to `undefined`, Angular assumes you intend to leave the body as is. -That is not what you want. -If you set the cloned request body to `null`, Angular knows you intend to clear the request body. +To do this, set the cloned request body to `null`. +Note that if you set the cloned request body to `undefined`, Angular assumes you intend to leave the body as is. ```javascript newReq = req.clone({ ... }); // body not mentioned => preserve original body @@ -650,7 +696,7 @@ If you set the cloned request body to `null`, Angular knows you intend to clear newReq = req.clone({ body: null }); // clear the body ``` -#### Set default headers +### Setting default headers Apps often use an interceptor to set default headers on outgoing requests. @@ -677,10 +723,9 @@ An interceptor that alters headers can be used for a number of different operati * Caching behavior; for example, `If-Modified-Since` * XSRF protection -#### Logging +### Using interceptors for logging -Because interceptors can process the request and response _together_, they can do things like time and log -an entire HTTP operation. +Because interceptors can process the request and response _together_, they can do things like time and log an entire HTTP operation. Consider the following `LoggingInterceptor`, which captures the time of the request, the time of the response, and logs the outcome with the elapsed time @@ -698,14 +743,16 @@ and reports the outcome to the `MessageService`. Neither `tap` nor `finalize` touch the values of the observable stream returned to the caller. -#### Caching +{@a caching} + +### Using interceptors for caching Interceptors can handle requests by themselves, without forwarding to `next.handle()`. For example, you might decide to cache certain requests and responses to improve performance. You can delegate caching to an interceptor without disturbing your existing data services. -The `CachingInterceptor` demonstrates this approach. +The `CachingInterceptor` in the following example demonstrates this approach. -The `isCachable()` function determines if the request is cachable. +* The `isCachable()` function determines if the request is cachable. In this sample, only GET requests to the npm package search api are cachable. -If the request is not cachable, the interceptor simply forwards the request +* If the request is not cachable, the interceptor simply forwards the request to the next handler in the chain. -If a cachable request is found in the cache, the interceptor returns an `of()` _observable_ with +* If a cachable request is found in the cache, the interceptor returns an `of()` _observable_ with the cached response, by-passing the `next` handler (and all other interceptors downstream). -If a cachable request is not in cache, the code calls `sendRequest`. +* If a cachable request is not in cache, the code calls `sendRequest()`. +This function creates a [request clone](#immutability) without headers (because the npm API forbids them). +It forwards the clone of the request to `next.handle()` which ultimately calls the server and returns the server's response. {@a send-request} -The `sendRequest` function creates a [request clone](#immutability) without headers -because the npm api forbids them. - -It forwards that request to `next.handle()` which ultimately calls the server and -returns the server's response. - -Note how `sendRequest` _intercepts the response_ on its way back to the application. -It _pipes_ the response through the `tap()` operator, -whose callback adds the response to the cache. +Note how `sendRequest()` intercepts the response on its way back to the application. +It pipes the response through the `tap()` operator, whose callback adds the response to the cache. The original response continues untouched back up through the chain of interceptors to the application caller. @@ -747,16 +789,13 @@ Data services, such as `PackageSearchService`, are unaware that some of their `HttpClient` requests actually return cached responses. {@a cache-refresh} -#### Return a multi-valued _Observable_ +### Using interceptors to request multiple values -The `HttpClient.get()` method normally returns an _observable_ -that either emits the data or an error. -Some folks describe it as a "_one and done_" observable. +The `HttpClient.get()` method normally returns an observable that emits a single value, either the data or an error. +An interceptor can change this to an observable that emits [multiple values](guide/observables). -But an interceptor can change this to an _observable_ that emits more than once. - -A revised version of the `CachingInterceptor` optionally returns an _observable_ that -immediately emits the cached response, sends the request to the NPM web API anyway, +The following revised version of the `CachingInterceptor` optionally returns an observable that +immediately emits the cached response, sends the request on to the npm web API, and emits again later with the updated search results. -The _cache-then-refresh_ option is triggered by the presence of a **custom `x-refresh` header**. -
+The _cache-then-refresh_ option is triggered by the presence of a custom `x-refresh` header. + A checkbox on the `PackageSearchComponent` toggles a `withRefresh` flag, which is one of the arguments to `PackageSearchService.search()`. That `search()` method creates the custom `x-refresh` header @@ -778,128 +817,19 @@ and adds it to the request before calling `HttpClient.get()`. The revised `CachingInterceptor` sets up a server request whether there's a cached value or not, using the same `sendRequest()` method described [above](#send-request). -The `results$` observable will make the request when subscribed. +The `results$` observable makes the request when subscribed. -If there's no cached value, the interceptor returns `results$`. +* If there's no cached value, the interceptor returns `results$`. -If there is a cached value, the code _pipes_ the cached response onto +* If there is a cached value, the code _pipes_ the cached response onto `results$`, producing a recomposed observable that emits twice, the cached response first (and immediately), followed later by the response from the server. -Subscribers see a sequence of _two_ responses. +Subscribers see a sequence of two responses. -### Configuring the request +{@a report-progress} -Other aspects of an outgoing request can be configured via the options object -passed as the last argument to the `HttpClient` method. - -In [Adding headers](#adding-headers), the `HeroesService` set the default headers by -passing an options object (`httpOptions`) to its save methods. -You can do more. - -#### URL query strings - -In this section, you will see how to use the `HttpParams` class to add URL query strings in your `HttpRequest`. - -The following `searchHeroes` method queries for heroes whose names contain the search term. -Start by importing `HttpParams` class. - - -import {HttpParams} from "@angular/common/http"; - - - - - -If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. -If the term were "foo", the GET request URL would be `api/heroes?name=foo`. - -The `HttpParams` are immutable so you'll have to save the returned value of the `.set()` method in order to update the options. - -#### Use `fromString` to create HttpParams - -You can also create HTTP parameters directly from a query string by using the `fromString` variable: - - -const params = new HttpParams({fromString: 'name=foo'}); - - -### Debouncing requests - -The sample includes an _npm package search_ feature. - -When the user enters a name in a search-box, the `PackageSearchComponent` sends -a search request for a package with that name to the NPM web API. - -Here's a pertinent excerpt from the template: - - - - -The `keyup` event binding sends every keystroke to the component's `search()` method. - -Sending a request for every keystroke could be expensive. -It's better to wait until the user stops typing and then send a request. -That's easy to implement with RxJS operators, as shown in this excerpt. - - - - -The `searchText$` is the sequence of search-box values coming from the user. -It's defined as an RxJS `Subject`, which means it is a multicasting `Observable` -that can also emit values for itself by calling `next(value)`, -as happens in the `search()` method. - -Rather than forward every `searchText` value directly to the injected `PackageSearchService`, -the code in `ngOnInit()` _pipes_ search values through three operators: - -1. `debounceTime(500)` - wait for the user to stop typing (1/2 second in this case). - -2. `distinctUntilChanged()` - wait until the search text changes. - -3. `switchMap()` - send the search request to the service. - -The code sets `packages$` to this re-composed `Observable` of search results. -The template subscribes to `packages$` with the [AsyncPipe](api/common/AsyncPipe) -and displays search results as they arrive. - -A search value reaches the service only if it's a new value and the user has stopped typing. - -
- -The `withRefresh` option is explained [below](#cache-refresh). - -
- -#### _switchMap()_ - -The `switchMap()` operator has three important characteristics. - -1. It takes a function argument that returns an `Observable`. -`PackageSearchService.search` returns an `Observable`, as other data service methods do. - -2. If a previous search request is still _in-flight_ (as when the network connection is poor), -it cancels that request and sends a new one. - -3. It returns service responses in their original request order, even if the -server returns them out of order. - -
- -If you think you'll reuse this debouncing logic, -consider moving it to a utility function or into the `PackageSearchService` itself. - -
- -### Listening to progress events +## Tracking and showing request progress Sometimes applications transfer large amounts of data and those transfers can take a long time. File uploads are a typical example. @@ -916,15 +846,15 @@ with the `reportProgress` option set true to enable tracking of progress events.
-Every progress event triggers change detection, so only turn them on if you truly intend to report progress in the UI. +Every progress event triggers change detection, so only turn them on if you need to report progress in the UI. -When using [`HttpClient#request()`](api/common/http/HttpClient#request) with an HTTP method, configure with +When using [`HttpClient.request()`](api/common/http/HttpClient#request) with an HTTP method, configure with [`observe: 'events'`](api/common/http/HttpClient#request) to see all events, including the progress of transfers.
Next, pass this request object to the `HttpClient.request()` method, which -returns an `Observable` of `HttpEvents`, the same events processed by interceptors: +returns an `Observable` of `HttpEvents` (the same events processed by [interceptors](#interceptor-events)). +## Optimizing server interaction with debouncing + +If you need to make an HTTP request in response to user input, it's not efficient to send a request for every keystroke. +It's better to wait until the user stops typing and then send a request. +This technique is known as debouncing. + +Consider the following template, which lets a user enter a search term to find an npm package by name. +When the user enters a name in a search-box, the `PackageSearchComponent` sends +a search request for a package with that name to the npm web API. + + + + +Here, the `keyup` event binding sends every keystroke to the component's `search()` method. +The following snippet implements debouncing for this input using RxJS operators. + + + + +The `searchText$` is the sequence of search-box values coming from the user. +It's defined as an RxJS `Subject`, which means it is a multicasting `Observable` +that can also emit values for itself by calling `next(value)`, +as happens in the `search()` method. + +Rather than forward every `searchText` value directly to the injected `PackageSearchService`, +the code in `ngOnInit()` pipes search values through three operators, so that a search value reaches the service only if it's a new value and the user has stopped typing. + +* `debounceTime(500)`&emdash;Wait for the user to stop typing (1/2 second in this case). + +* `distinctUntilChanged()`&emdash;Wait until the search text changes. + +* `switchMap()`&emdash;Send the search request to the service. + +The code sets `packages$` to this re-composed `Observable` of search results. +The template subscribes to `packages$` with the [AsyncPipe](api/common/AsyncPipe) +and displays search results as they arrive. + +
+ +See [Using interceptors to request multiple values](#cache-refresh) for more about the `withRefresh` option. + +
+ +### Using the *switchMap()* operator + +The `switchMap()` operator takes a function argument that returns an `Observable`. +In the example, `PackageSearchService.search` returns an `Observable`, as other data service methods do. +If a previous search request is still in-flight (as when the network connection is poor), +the operator cancels that request and sends a new one. + +Note that `switchMap()` returns service responses in their original request order, even if the +server returns them out of order. + + +
+ +If you think you'll reuse this debouncing logic, +consider moving it to a utility function or into the `PackageSearchService` itself. + +
+ + ## Security: XSRF protection [Cross-Site Request Forgery (XSRF or CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website. @@ -985,6 +983,7 @@ use `HttpClientXsrfModule.withOptions()` to override the defaults. region="xsrf">
+{@a testing-requests} ## Testing HTTP requests As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server. @@ -1008,7 +1007,7 @@ There are also tests of an application data service that call `HttpClient` in
-### Setup +### Setup for testing To begin testing calls to `HttpClient`, import the `HttpClientTestingModule` and the mocking controller, `HttpTestingController`, diff --git a/aio/content/navigation.json b/aio/content/navigation.json index 6f50a13020..75d1ed547f 100644 --- a/aio/content/navigation.json +++ b/aio/content/navigation.json @@ -401,8 +401,13 @@ }, { "url": "guide/http", +<<<<<<< HEAD "title": "Access Servers over HTTP", "tooltip": "Use HTTP to talk to a remote server." +======= + "title": "Server Interaction", + "tooltip": "Use HTTP to communicate with a remote server." +>>>>>>> docs: update http guide }, { "url": "guide/router",