{ "id": "guide/http", "title": "Communicating with backend services using HTTP", "contents": "\n\n\n
Most front-end applications need to communicate with a server over the HTTP protocol, in order to download or upload data and access other back-end services.\nAngular provides a simplified client HTTP API for Angular applications, the HttpClient
service class in @angular/common/http
.
The HTTP client service offers the following major features.
\nBefore working with the HttpClientModule
, you should have a basic understanding of the following:
Before you can use HttpClient
, you need to import the Angular HttpClientModule
.\nMost 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 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
The sample app does not require a data server.\nIt relies on the\nAngular in-memory-web-api,\nwhich replaces the HttpClient module's HttpBackend
.\nThe replacement service simulates the behavior of a REST-like backend.
Look at the AppModule
imports to see how it is configured.
Use the HttpClient.get()
method to fetch data from a server.\nThe asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.\nThe 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.
Important options include the observe and responseType properties.
\nYou can use the options
object to configure various other aspects of an outgoing request.\nIn 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, and the reportProgress
option to listen for progress events when transferring large amounts of data.
Applications often request JSON data from a server.\nIn the ConfigService
example, the app needs a configuration file on the server, config.json
,\nthat specifies resource URLs.
To fetch this kind of data, the get()
call needs the following options: {observe: 'body', responseType: 'json'}
.\nThese are the default values for those options, so the following examples do not pass the options object.\nLater sections show some of the additional option possibilities.
The example conforms to the best practices for creating scalable solutions by defining a re-usable injectable service to perform the data-handling functionality.\nIn addition to fetching data, the service can post-process the data, add error handling, and add retry logic.
\nThe ConfigService
fetches this file using the HttpClient.get()
method.
The ConfigComponent
injects the ConfigService
and calls\nthe getConfig
service method.
Because the service method returns an Observable
of configuration data,\nthe component subscribes to the method's return value.\nThe subscription callback performs minimal post-processing.\nIt copies the data fields into the component's config
object, which is data-bound in the component template for display.
You can structure your HttpClient
request to declare the type of the response object, to make consuming the output easier and more obvious.\nSpecifying the response type acts as a type assertion at compile time.
Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.\nThis 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.
\nTo specify the response object type, first define an interface with the required properties.\nUse an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.
\nNext, specify that interface as the HttpClient.get()
call's type parameter in the service.
When you pass an interface as a type parameter to the HttpClient.get()
method, you can 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.
The callback in the updated component method receives a typed data object, which is\neasier and safer to consume:
\nTo access properties that are defined in an interface, you must explicitly convert the plain object you get from the JSON to the required response type.\nFor example, the following subscribe
callback receives data
as an Object, and then type-casts it in order to access the properties.
The types of the observe
and response
options are string unions, rather than plain strings.
This can cause confusion. For example:
\nIn the second case, TypeScript infers the type of options
to be {responseType: string}
.\nThe type is too wide to pass to HttpClient.get
which is expecting the type of responseType
to be one of the specific strings.\nHttpClient
is typed explicitly this way so that the compiler can report the correct return type based on the options you provided.
Use as const
to let TypeScript know that you really do mean to use a constant string type:
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.
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.
\nTell 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 contained in the body.
The component's showConfigResponse()
method displays the response headers as well as the configuration:
As you can see, the response object has a body
property of the correct type.
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
.\nFollow 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.\nIn the following example, the searchHeroes()
method uses a JSONP request to query for heroes whose names contain the search term.
This request passes the heroesURL
as the first parameter and the callback function name as the second parameter.\nThe 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.\nIn 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 (as in \"wiretap\") 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.
If the request fails on 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.
\nWhen 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.
\n\nAn app should give the user useful feedback when data access fails.\nA raw error object is not particularly useful as feedback.\nIn addition to detecting that an error has occurred, you need to get error details and use those details to compose a user-friendly response.
\nTwo types of errors can occur.
\nThe server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error responses.
\nSomething 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.
HttpClient
captures both kinds of errors in its HttpErrorResponse
. You can inspect that response to identify the error's cause.
The following example defines an error handler in the previously defined ConfigService.
\nThe handler returns an RxJS ErrorObservable
with a user-friendly error message.\nThe following code updates the getConfig()
method, using a pipe to send all observables returned by the HttpClient.get()
call to the error handler.
Sometimes the error is transient and goes away automatically if you try again.\nFor example, network interruptions are common in mobile scenarios, and trying again\ncan produce a successful result.
\nThe RxJS library offers several retry operators.\nFor 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.
The following example shows how you can pipe a failed request to the retry()
operator before passing it to the error handler.
In addition to fetching data from a server, HttpClient
supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.
The sample app for this guide includes a simplified version of the \"Tour of Heroes\" example\nthat fetches heroes and enables users to add, delete, and update them.\nThe following sections show examples of the data-update methods from the sample's HeroesService
.
Apps often send data to a server with a POST request when submitting a form.\nIn the following example, the HeroesService
makes an HTTP POST request when adding a hero to the database.
The HttpClient.post()
method is similar to get()
in that it has a type parameter, which you can use to specify that you expect the server to return data of a given type. The method takes a resource URL and two additional parameters:
The example catches errors as described above.
\nThe HeroesComponent
initiates the actual POST operation by subscribing to\nthe Observable
returned by this service method.
When the server responds successfully with the newly added hero, the component adds\nthat hero to the displayed heroes
list.
This application deletes a hero with the HttpClient.delete
method by passing the hero's id\nin the request URL.
The HeroesComponent
initiates the actual DELETE operation by subscribing to\nthe Observable
returned by this service method.
The component isn't expecting a result from the delete operation, so it subscribes without a callback. Even though you are not using the result, you still have to subscribe. Calling the subscribe()
method executes the observable, which is what initiates the DELETE request.
You must call subscribe() or nothing happens. Just calling HeroesService.deleteHero()
does not initiate the DELETE request.
Always subscribe!
\nAn HttpClient
method does not begin its HTTP request until you call subscribe()
on the observable returned by that method. This is true for all HttpClient
methods.
The AsyncPipe
subscribes (and unsubscribes) for you automatically.
All observables returned from HttpClient
methods are cold by design.\nExecution of the HTTP request is deferred, allowing you to extend the\nobservable with additional operations such as tap
and catchError
before anything actually happens.
Calling subscribe(...)
triggers execution of the observable and causes\nHttpClient
to compose and send the HTTP request to the server.
You can think of these observables as blueprints for actual HTTP requests.
\nIn fact, each subscribe()
initiates a separate, independent execution of the observable.\nSubscribing twice results in two HTTP requests.
An app can send PUT requests using the HTTP client service.\nThe following HeroesService
example, like the POST example, replaces a resource with updated data.
As for any of the HTTP methods that return an observable, the caller, HeroesComponent.update()
must subscribe()
to the observable returned from the HttpClient.put()
in order to initiate the request.
Many servers require extra headers for save operations.\nFor example, a server might require an authorization token, or \"Content-Type\" header to explicitly declare the MIME type of the request body.
\nThe HeroesService
defines such headers in an httpOptions
object that are passed\nto every HttpClient
save method.
You can't directly modify the existing headers within the previous options\nobject because instances of the HttpHeaders
class are immutable.\nUse 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.
\nUse 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.
If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter.\nIf 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:
With interception, you declare interceptors that inspect and transform HTTP requests from your application to a server.\nThe same interceptors can also inspect and transform a server's responses on their way back to the application.\nMultiple interceptors form a forward-and-backward chain of request/response handlers.
\nInterceptors can perform a variety of implicit tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response.
\nWithout interception, developers would have to implement these tasks explicitly\nfor each HttpClient
method call.
To implement an interceptor, declare a class that implements the intercept()
method of the HttpInterceptor
interface.
Here is a do-nothing noop interceptor that simply passes the request through without touching it:\n
The intercept
method transforms a request into an Observable
that eventually returns the HTTP response.\nIn this sense, each interceptor is fully capable of handling the request entirely by itself.
Most interceptors inspect the request on the way in and forward the (perhaps altered) request to the handle()
method of the next
object which implements the HttpHandler
interface.
Like intercept()
, the handle()
method transforms an HTTP request into an Observable
of HttpEvents
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 represents the next interceptor in the chain of interceptors.\nThe final next
in the chain is the HttpClient
backend handler that sends the request to the server and receives the server's response.
Most interceptors call next.handle()
so that the request flows through to the next interceptor and, eventually, the backend handler.\nAn interceptor could skip calling next.handle()
, short-circuit the chain, and return its own Observable
with an artificial server response.
This is a common middleware pattern found in frameworks such as Express.js.
\nThe NoopInterceptor
is a service managed by Angular's dependency injection (DI) system.\nLike other services, you must provide the interceptor class before the app can use it.
Because interceptors are (optional) dependencies of the HttpClient
service,\nyou must provide them in the same injector (or a parent of the injector) that provides HttpClient
.\nInterceptors provided after DI creates the HttpClient
are ignored.
This app provides HttpClient
in the app's root injector, as a side-effect of importing the HttpClientModule
in AppModule
.\nYou should provide interceptors in AppModule
as well.
After importing the HTTP_INTERCEPTORS
injection token from @angular/common/http
,\nwrite the NoopInterceptor
provider like this:
Note the multi: true
option.\nThis required setting tells Angular that HTTP_INTERCEPTORS
is a token for a multiprovider\nthat injects an array of values, rather than a single value.
You could add this provider directly to the providers array of the AppModule
.\nHowever, it's rather verbose and there's a good chance that\nyou'll create more interceptors and provide them in the same way.\nYou must also pay close attention to the order\nin which you provide these interceptors.
Consider creating a \"barrel\" file that gathers all the interceptor providers into an httpInterceptorProviders
array, starting with this first one, the NoopInterceptor
.
Then import and add it to the AppModule
providers array like this:
As you create new interceptors, add them to the httpInterceptorProviders
array and\nyou won't have to revisit the AppModule
.
There are many more interceptors in the complete sample code.
\nAngular applies interceptors in the order that you provide them.\nFor example, consider a situation in which you want to handle the authentication of your HTTP requests and log them before sending them to a server. To accomplish this task, you could provide an AuthInterceptor
service and then a LoggingInterceptor
service.\nOutgoing requests would flow from the AuthInterceptor
to the LoggingInterceptor
.\nResponses from these requests would flow in the other direction, from LoggingInterceptor
back to AuthInterceptor
.\nThe following is a visual representation of the process:
The last interceptor in the process is always the HttpBackend
that handles communication with the server.
You cannot change the order or remove interceptors later.\nIf you need to enable and disable an interceptor dynamically, you'll have to build that capability into the interceptor itself.
\n\nMost HttpClient
methods return observables of HttpResponse<any>
.\nThe HttpResponse
class itself is actually an event, whose type is HttpEventType.Response
.\nA single HTTP request can, however, generate multiple events of other types, including upload and download progress events.\nThe methods HttpInterceptor.intercept()
and HttpHandler.handle()
return observables of HttpEvent<any>
.
Many interceptors are only concerned with the outgoing request and return the event stream from next.handle()
without modifying it.\nSome interceptors, however, need to examine and modify the response from next.handle()
; these operations can see all of these events in the stream.
Although interceptors are capable of modifying requests and responses,\nthe HttpRequest
and HttpResponse
instance properties are readonly
,\nrendering them largely immutable.\nThey are immutable for a good reason: an app might retry a request several times before it succeeds, which means that the interceptor chain can re-process the same request multiple times.\nIf 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.
Your interceptor should return every event without modification unless it has a compelling reason to do otherwise.
\nTypeScript prevents you from setting HttpRequest
read-only properties.
If you must alter a request, clone it first and modify the clone before passing it to next.handle()
.\nYou can clone and modify the request in a single step, as shown in the following example.
The clone()
method's hash argument allows you to mutate specific properties of the request while copying the others.
The readonly
assignment guard can't prevent deep updates and, in particular,\nit can't prevent you from modifying a property of a request body object.
If you must modify the request body, follow these steps.
\nclone()
method.Sometimes you need to clear the request body rather than replace it.\nTo do this, set the cloned request body to null
.
Tip: If you set the cloned request body to undefined
, Angular assumes you intend to leave the body as is.
Below are a number of common uses for interceptors.
\nApps often use an interceptor to set default headers on outgoing requests.
\nThe sample app has an AuthService
that produces an authorization token.\nHere is its AuthInterceptor
that injects that service to get the token and\nadds an authorization header with that token to every outgoing request:
The practice of cloning a request to set new headers is so common that\nthere's a setHeaders
shortcut for it:
An interceptor that alters headers can be used for a number of different operations, including:
\nIf-Modified-Since
Because interceptors can process the request and response together, they can perform tasks such as timing and logging an entire HTTP operation.
\nConsider the following LoggingInterceptor
, which captures the time of the request,\nthe time of the response, and logs the outcome with the elapsed time\nwith the injected MessageService
.
The RxJS tap
operator captures whether the request succeeded or failed.\nThe RxJS finalize
operator is called when the response observable either errors or completes (which it must),\nand reports the outcome to the MessageService
.
Neither tap
nor finalize
touch the values of the observable stream returned to the caller.
Interceptors can be used to replace the built-in JSON parsing with a custom implementation.
\nThe CustomJsonInterceptor
in the following example demonstrates how to achieve this.\nIf the intercepted request expects a 'json'
response, the reponseType
is changed to 'text'
\nto disable the built-in JSON parsing. Then the response is parsed via the injected JsonParser
.
You can then implement your own custom JsonParser
.\nHere is a custom JsonParser that has a special date reviver.
You provide the CustomParser
along with the CustomJsonInterceptor
.
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.\nYou can delegate caching to an interceptor without disturbing your existing data services.
\nThe CachingInterceptor
in the following example demonstrates this approach.
The isCacheable()
function determines if the request is cacheable.\nIn this sample, only GET requests to the npm package search api are cacheable.
If the request is not cacheable, the interceptor simply forwards the request\nto the next handler in the chain.
\nIf a cacheable request is found in the cache, the interceptor returns an of()
observable with\nthe cached response, by-passing the next
handler (and all other interceptors downstream).
If a cacheable request is not in cache, the code calls sendRequest()
.\nThis function creates a request clone without headers, because the npm API forbids them.\nThe function then forwards the clone of the 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.\nThis method 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\nto the application caller.
\nData services, such as PackageSearchService
, are unaware that\nsome of their HttpClient
requests actually return cached responses.
The HttpClient.get()
method normally returns an observable that emits a single value, either the data or an error.\nAn interceptor can change this to an observable that emits multiple values.
The following revised version of the CachingInterceptor
optionally returns an observable that\nimmediately emits the cached response, sends the request on to the npm web API,\nand emits again later with the updated search results.
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,\nwhich is one of the arguments to PackageSearchService.search()
.\nThat search()
method creates the custom x-refresh
header\nand adds it to the request before calling HttpClient.get()
.
The revised CachingInterceptor
sets up a server request\nwhether there's a cached value or not,\nusing the same sendRequest()
method described above.\nThe results$
observable makes the request when subscribed.
If there's no cached value, the interceptor returns results$
.
If there is a cached value, the code pipes the cached response onto\nresults$
, producing a recomposed observable that emits twice,\nthe cached response first (and immediately), followed later\nby the response from the server.\nSubscribers see a sequence of two responses.
Sometimes applications transfer large amounts of data and those transfers can take a long time.\nFile uploads are a typical example.\nYou can give the users a better experience by providing feedback on the progress of such transfers.
\nTo make a request with progress events enabled, you can create an instance of HttpRequest
\nwith the reportProgress
option set true to enable tracking of progress events.
Tip: Every progress event triggers change detection, so only turn them on if you need to report progress in the UI.
\nWhen using HttpClient.request()
with an HTTP method, configure the method with\nobserve: 'events'
to see all events, including the progress of transfers.
Next, pass this request object to the HttpClient.request()
method, which\nreturns an Observable
of HttpEvents
(the same events processed by interceptors).
The getEventMessage
method interprets each type of HttpEvent
in the event stream.
The sample app for this guide doesn't have a server that accepts uploaded files.\nThe UploadInterceptor
in app/http-interceptors/upload-interceptor.ts
\nintercepts and short-circuits upload requests\nby returning an observable of simulated events.
If you need to make an HTTP request in response to user input, it's not efficient to send a request for every keystroke.\nIt's better to wait until the user stops typing and then send a request.\nThis technique is known as debouncing.
\nConsider the following template, which lets a user enter a search term to find an npm package by name.\nWhen the user enters a name in a search-box, the PackageSearchComponent
sends\na 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 type of $event.target
is only EventTarget
in the template.\nIn the getValue()
method, the target is cast to an HTMLInputElement
to allow type-safe access to its value
property.
The following snippet implements debouncing for this input using RxJS operators.
\nThe searchText$
is the sequence of search-box values coming from the user.\nIt's defined as an RxJS Subject
, which means it is a multicasting Observable
\nthat can also emit values for itself by calling next(value)
,\nas happens in the search()
method.
Rather than forward every searchText
value directly to the injected PackageSearchService
,\nthe 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)
—Wait for the user to stop typing (1/2 second in this case).
distinctUntilChanged()
—Wait until the search text changes.
switchMap()
—Send the search request to the service.
The code sets packages$
to this re-composed Observable
of search results.\nThe template subscribes to packages$
with the AsyncPipe\nand displays search results as they arrive.
See Using interceptors to request multiple values for more about the withRefresh
option.
The switchMap()
operator takes a function argument that returns an Observable
.\nIn the example, PackageSearchService.search
returns an Observable
, as other data service methods do.\nIf a previous search request is still in-flight (as when the network connection is poor),\nthe operator cancels that request and sends a new one.
Note that switchMap()
returns service responses in their original request order, even if the\nserver returns them out of order.
If you think you'll reuse this debouncing logic,\nconsider moving it to a utility function or into the PackageSearchService
itself.
Cross-Site Request Forgery (XSRF or CSRF) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.\nHttpClient
supports a common mechanism used to prevent XSRF attacks.\nWhen performing HTTP requests, an interceptor reads a token from a cookie, by default XSRF-TOKEN
, and sets it as an HTTP header, X-XSRF-TOKEN
.\nSince only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
By default, an interceptor sends this header on all mutating requests (such as POST)\nto relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.
\nTo take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN
on either the page load or the first GET request.\nOn subsequent requests the server can verify that the cookie matches the X-XSRF-TOKEN
HTTP header, and therefore be sure that only code running on your domain could have sent the request.\nThe token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens.\nSet the token to a digest of your site's authentication cookie with a salt for added security.
In order to prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.
\nHttpClient
supports only the client half of the XSRF protection scheme.\nYour backend service must be configured to set the cookie for your page, and to verify that\nthe header is present on all eligible requests.\nFailing to do so renders Angular's default protection ineffective.
If your backend service uses different names for the XSRF token cookie or header,\nuse HttpClientXsrfModule.withOptions()
to override the defaults.
As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server.\nThe @angular/common/http/testing
library makes it straightforward to set up such mocking.
Angular's HTTP testing library is designed for a pattern of testing in which the app executes code and makes requests first.\nThe test then expects that certain requests have or have not been made,\nperforms assertions against those requests,\nand finally provides responses by \"flushing\" each expected request.
\nAt the end, tests can verify that the app has made no unexpected requests.
\nYou can run
The tests described in this guide are in src/testing/http-client.spec.ts
.\nThere are also tests of an application data service that call HttpClient
in\nsrc/app/heroes/heroes.service.spec.ts
.
To begin testing calls to HttpClient
,\nimport the HttpClientTestingModule
and the mocking controller, HttpTestingController
,\nalong with the other symbols your tests require.
Then add the HttpClientTestingModule
to the TestBed
and continue with\nthe setup of the service-under-test.
Now requests made in the course of your tests hit the testing backend instead of the normal backend.
\nThis setup also calls TestBed.inject()
to inject the HttpClient
service and the mocking controller\nso they can be referenced during the tests.
Now you can write a test that expects a GET Request to occur and provides a mock response.
\nThe last step, verifying that no requests remain outstanding, is common enough for you to move it into an afterEach()
step:
If matching by URL isn't sufficient, it's possible to implement your own matching function.\nFor example, you could look for an outgoing request that has an authorization header:
\nAs with the previous expectOne()
,\nthe test fails if 0 or 2+ requests satisfy this predicate.
If you need to respond to duplicate requests in your test, use the match()
API instead of expectOne()
.\nIt takes the same arguments but returns an array of matching requests.\nOnce returned, these requests are removed from future matching and\nyou are responsible for flushing and verifying them.
You should test the app's defenses against HTTP requests that fail.
\nCall request.flush()
with an error message, as seen in the following example.
Alternatively, you can call request.error()
with an ErrorEvent
.