Angular http error codes

The modern web developer’s platform. Contribute to angular/angular development by creating an account on GitHub.

Communicating with backend services using HTTP

Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services.
Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http.

The HTTP client service offers the following major features.

  • The ability to request typed response objects
  • Streamlined error handling
  • Testability features
  • Request and response interception

Prerequisites

Before working with the HttpClientModule, you should have a basic understanding of the following:

  • TypeScript programming
  • Usage of the HTTP protocol
  • Angular application-design fundamentals, as described in Angular Concepts
  • Observable techniques and operators.
    See the 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 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, which replaces the HttpClient module’s HttpBackend.
The replacement service simulates the behavior of a REST-like backend.

Look at the AppModule imports to see how it is configured.

Requesting data from a server

Use the HttpClient.get() method to fetch data from a server.
The asynchronous 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 is used to configure the request.

options: {
headers?: HttpHeaders | {[header: string]: string | string[]},
observe?: ‘body’ | ‘events’ | ‘response’,
params?: HttpParams|{[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>},
reportProgress?: boolean,
responseType?: ‘arraybuffer’|’blob’|’json’|’text’,
withCredentials?: boolean,
}

Important options include the observe and responseType properties.

  • The observe option specifies how much of the response to return
  • The responseType option specifies the format in which to return data

Use the options object to configure various other aspects of an outgoing request.
In 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.
In the ConfigService example, the app needs a configuration file on the server, config.json, that specifies resource URLs.

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 the best practices for creating scalable solutions by defining a re-usable injectable service 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.

The ConfigService fetches this file using the HttpClient.get() method.

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.

Starting the request

For all HttpClient methods, the method doesn’t begin its HTTP request until you call subscribe() on the observable the method returns.

This is true for all HttpClient methods.

You should always unsubscribe from an observable when a component is destroyed.

All observables returned from HttpClient methods are cold by design.
Execution of the HTTP request is deferred, letting you extend the observable with additional operations such as tap and catchError before anything actually happens.

Calling subscribe() triggers execution of the observable and causes HttpClient to compose and send the HTTP request to the server.

Think of these observables as blueprints for actual HTTP requests.

In fact, each subscribe() initiates a separate, independent execution of the observable.
Subscribing twice results in two HTTP requests.

const req = http.get<Heroes>(‘/api/heroes’);
// 0 requests made — .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.

Requesting a typed response

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 at compile time.

Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.
This is a build-time check and doesn’t guarantee that the server actually responds 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, because the response is a plain object that cannot be automatically converted to an instance of a class.

Next, 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, 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 easier and safer to consume:

To 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.
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,
});

observe and response types

The types of the observe and response options are string unions, rather than plain strings.

options: {

observe?: ‘body’ | ‘events’ | ‘response’,

responseType?: ‘arraybuffer’|’blob’|’json’|’text’,

}

This can cause confusion.
For example:

// this works
client.get(‘/foo’, {responseType: ‘text’})

// but this does NOT work
const options = {
responseType: ‘text’,
};
client.get(‘/foo’, options)

In the second case, TypeScript infers the type of options to be {responseType: string}.
The type is too wide to pass to HttpClient.get which is expecting the type of responseType to be one of the specific strings.
HttpClient 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:

const options = {
responseType: ‘text’ as const,
};
client.get(‘/foo’, options);

Reading the full response

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.

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 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.

Making a JSONP 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 = &dollar;{this.heroesURL}?&dollar;{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.

Requesting 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.

Handling request errors

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.

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.

Getting error details

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 need to get error details and use those details to 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.

  • 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 have status set to 0 and the error property contains a ProgressEvent object, whose type might provide further information.

HttpClient captures both kinds of errors in its HttpErrorResponse.
Inspect that response to identify the error’s cause.

The following example defines an error handler in the previously defined ConfigService.

The handler returns an RxJS ErrorObservable with a user-friendly error message.
The following code updates the getConfig() method, using a pipe to send all observables returned by the HttpClient.get() call to the error handler.

Retrying a failed request

Sometimes the error is transient and goes away automatically if you try again.
For example, network interruptions are common in mobile scenarios, and trying again can produce a successful result.

The RxJS library offers several retry operators.
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.

The following example shows how to pipe a failed request to the retry() operator before passing it to the error handler.

Sending data to a server

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 an abridged version of the «Tour of Heroes» example that fetches heroes and enables users to add, delete, and update them.
The following sections show examples of the data-update methods from the sample’s HeroesService.

Making a POST request

Apps often send data to a server with a POST request when submitting a form.
In 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:

Parameter Details
body The data to POST in the body of the request.
options An object containing method options which, in this case, specify required headers.

The example catches errors as described above.

The HeroesComponent initiates the actual POST operation by subscribing to the Observable returned by this service method.

When the server responds successfully with the newly added hero, the component adds that hero to the displayed heroes list.

Making a DELETE request

This application deletes a hero with the HttpClient.delete method by passing the hero’s ID in the request URL.

The HeroesComponent initiates the actual DELETE operation by subscribing to the 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.

Making a PUT request

An app can send PUT requests using the HTTP client service.
The 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.

Adding and updating headers

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.

Adding headers

The HeroesService defines such headers in an httpOptions object that are 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 expires, you can update the authorization header before making the next request.

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’});

Intercepting requests and responses

With interception, you declare interceptors that inspect and transform HTTP requests from your application to a server.
The same interceptors can 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.

Without interception, developers would have to implement these tasks explicitly for each HttpClient method call.

Write an interceptor

To implement an interceptor, declare a class that implements the intercept() method of the HttpInterceptor interface.

Here is a do-nothing noop interceptor that passes the request through without touching it:

The intercept method transforms a request into an Observable that eventually returns the HTTP response.
In 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 potentially altered request to the handle() method of the next object which implements the HttpHandler interface.

export abstract class HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}

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 calls next.handle() with the original request and returns the observable without doing a thing.

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.

Most interceptors call next.handle() so that the request flows through to the next interceptor and, eventually, the backend handler.
An 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.

Provide the interceptor

The NoopInterceptor is a service managed by Angular’s dependency injection (DI) system.
Like other services, you must provide the interceptor class before the app can use it.

Because interceptors are optional dependencies of the HttpClient service, you must provide them in the same injector or a parent of the injector that provides HttpClient.
Interceptors 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.
You should provide interceptors in AppModule as well.

After importing the HTTP_INTERCEPTORS injection token from @angular/common/http, write the NoopInterceptor provider like this:

Notice the multi: true option.
This required setting tells Angular that HTTP_INTERCEPTORS is a token for a multiprovider that injects an array of values, rather than a single value.

You could add this provider directly to the providers array of the AppModule.
However, it’s rather verbose and there’s a good chance that you’ll create more interceptors and provide them in the same way.
You must also pay close attention to the order in 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 you won’t have to revisit the AppModule.

There are many more interceptors in the complete sample code.

Interceptor order

Angular applies interceptors in the order that you provide them.
For 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.
Outgoing requests would flow from the AuthInterceptor to the LoggingInterceptor.
Responses from these requests would flow in the other direction, from LoggingInterceptor back to AuthInterceptor.
The following is a visual representation of the process:

Interceptor in order of HttpClient, AuthInterceptor, AuthInterceptor, HttpBackend, Server, and back in opposite order to show the two-way flow

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.
If you need to enable and disable an interceptor dynamically, you’ll have to build that capability into the interceptor itself.

Handling interceptor events

Most HttpClient methods return observables of HttpResponse<any>.
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.
The 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.
Some 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, the HttpRequest and HttpResponse instance properties are readonly, rendering them largely immutable.
They 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.
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.

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.

// Typescript disallows the following assignment because req.url is readonly
req.url = req.url.replace(‘http://’, ‘https://’);

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.

The clone() method’s hash argument lets you mutate specific properties of the request while copying the others.

Modifying a request body

The readonly assignment guard can’t prevent deep updates and, in particular, it can’t prevent you from modifying a property of a request body object.

req.body.name = req.body.name.trim(); // bad idea!

If you must modify the request body, follow these steps.

  1. Copy the body and make your change in the copy.
  2. Clone the request object, using its clone() method.
  3. Replace the clone’s body with the modified copy.

Clearing the request body in a clone

Sometimes you need to clear the request body rather than replace it.
To 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.

newReq = req.clone({ … }); // body not mentioned => preserve original body
newReq = req.clone({ body: undefined }); // preserve original body
newReq = req.clone({ body: null }); // clear the body

Http interceptor use-cases

Following are a number of common uses for interceptors.

Setting default headers

Apps often use an interceptor to set default headers on outgoing requests.

The sample app has an AuthService that produces an authorization token.
Here is its AuthInterceptor that injects that service to get the token and adds an authorization header with that token to every outgoing request:

The practice of cloning a request to set new headers is so common that there’s a setHeaders shortcut for it:

An interceptor that alters headers can be used for a number of different operations, including:

  • Authentication/authorization
  • Caching behavior; for example, If-Modified-Since
  • XSRF protection

Logging request and response pairs

Because interceptors can process the request and response together, they can perform tasks such as timing and logging 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
with the injected MessageService.

The RxJS tap operator captures whether the request succeeded or failed.
The RxJS finalize operator is called when the response observable either returns an error or completes and reports the outcome to the MessageService.

Neither tap nor finalize touch the values of the observable stream returned to the caller.

Custom JSON parsing

Interceptors can be used to replace the built-in JSON parsing with a custom implementation.

The CustomJsonInterceptor in the following example demonstrates how to achieve this.
If the intercepted request expects a 'json' response, the responseType is changed to 'text' to disable the built-in JSON parsing.
Then the response is parsed via the injected JsonParser.

You can then implement your own custom JsonParser.
Here is a custom JsonParser that has a special date reviver.

You provide the CustomParser along with the CustomJsonInterceptor.

Caching requests

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 in the following example demonstrates this approach.

  • The isCacheable() function determines if the request is cacheable.
    In this sample, only GET requests to the package search API are cacheable.

  • If the request is not cacheable, the interceptor forwards the request to the next handler in the chain

  • If a cacheable 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 cacheable request is not in cache, the code calls sendRequest().
    This function forwards the request to next.handle() which ultimately calls the server and returns the server’s response.

Notice how sendRequest() intercepts the response on its way back to the application.
This 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 to the application caller.

Data services, such as PackageSearchService, are unaware that some of their HttpClient requests actually return cached responses.

Using interceptors to request multiple values

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.

The following revised version of the CachingInterceptor optionally returns an observable that immediately emits the cached response, sends the request on to the package search 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.

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 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.
The 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 results$. This produces a recomposed observable that emits two responses, so subscribers will see a sequence of these two responses:
  • The cached response that’s emitted immediately
  • The response from the server, that’s emitted later

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.
You can give the users a better experience by providing feedback on the progress of such transfers.

To make a request with progress events enabled, create an instance of HttpRequest with 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.

When using HttpClient.request() with an HTTP method, configure the method with observe: 'events' 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).

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.
The UploadInterceptor in app/http-interceptors/upload-interceptor.ts intercepts and short-circuits upload requests by returning an observable of simulated 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 a 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 package search 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.
In the getValue() method, the target is cast to an HTMLInputElement to let type-safe have access to its value property.

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 stopped typing.

RxJS operators Details
debounceTime(500) Wait for the user to stop typing, which is 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.
The template subscribes to packages$ with the AsyncPipe and displays search results as they arrive.

See Using interceptors to request multiple values 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, such as when the network connection is poor, the operator cancels that request and sends a new one.

NOTE:
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) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
HttpClient supports a common mechanism used to prevent XSRF attacks.
When 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.
Because 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)
to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.

To 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.
On 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.
The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens.
Set the token to a digest of your site’s authentication cookie with a salt for added security.

To prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.

HttpClient supports only the client half of the XSRF protection scheme.
Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests.
Failing to do so renders Angular’s default protection ineffective.

Configuring custom cookie/header names

If your backend service uses different names for the XSRF token cookie or header, use HttpClientXsrfModule.withOptions() to override the defaults.

Testing HTTP requests

As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server.
The @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.
The test then expects that certain requests have or have not been made, performs assertions against those requests, and finally provides responses by «flushing» each expected request.

At the end, tests can verify that the app made no unexpected requests.

You can run these sample tests in a live coding environment.

The tests described in this guide are in src/testing/http-client.spec.ts.
There are also tests of an application data service that call HttpClient in src/app/heroes/heroes.service.spec.ts.

Setup for testing

To begin testing calls to HttpClient, import the HttpClientTestingModule and the mocking controller, HttpTestingController, along with the other symbols your tests require.

Then add the HttpClientTestingModule to the TestBed and continue with the setup of the service-under-test.

Now requests made in the course of your tests hit the testing backend instead of the normal backend.

This setup also calls TestBed.inject() to inject the HttpClient service and the mocking controller so they can be referenced during the tests.

Expecting and answering requests

Now you can write a test that expects a GET Request to occur and provides a mock response.

The last step, verifying that no requests remain outstanding, is common enough for you to move it into an afterEach() step:

Custom request expectations

If matching by URL isn’t sufficient, it’s possible to implement your own matching function.
For example, you could look for an outgoing request that has an authorization header:

As with the previous expectOne(), the test fails if 0 or 2+ requests satisfy this predicate.

Handling more than one request

If you need to respond to duplicate requests in your test, use the match() API instead of expectOne().
It takes the same arguments but returns an array of matching requests.
Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them.

Testing for errors

You should test the app’s defenses against HTTP requests that fail.

Call request.flush() with an error message, as seen in the following example.

Alternatively, call request.error() with a ProgressEvent.

Passing metadata to interceptors

Many interceptors require or benefit from configuration.
Consider an interceptor that retries failed requests.
By default, the interceptor might retry a request three times, but you might want to override this retry count for particularly error-prone or sensitive requests.

HttpClient requests contain a context that can carry metadata about the request.
This context is available for interceptors to read or modify, though it is not transmitted to the backend server when the request is sent.
This lets applications or other interceptors tag requests with configuration parameters, such as how many times to retry a request.

Creating a context token

Angular stores and retrieves a value in the context using an HttpContextToken.
You can create a context token using the new operator, as in the following example:

The lambda function () => 3 passed during the creation of the HttpContextToken serves two purposes:

  1. It lets TypeScript infer the type of this token:
    HttpContextToken<number>
    The request context is type-safe —reading a token from a request’s context returns a value of the appropriate type.

  2. It sets the default value for the token.
    This is the value that the request context returns if no other value was set for this token.
    Using a default value avoids the need to check if a particular value is set.

Setting context values when making a request

When making a request, you can provide an HttpContext instance, in which you have already set the context values.

Reading context values in an interceptor

Within an interceptor, you can read the value of a token in a given request’s context with HttpContext.get().
If you have not explicitly set a value for the token, Angular returns the default value specified in the token.

Contexts are mutable

Unlike most other aspects of HttpRequest instances, the request context is mutable and persists across other immutable transformations of the request.
This lets interceptors coordinate operations through the context.
For instance, the RetryInterceptor example could use a second context token to track how many errors occur during the execution of a given request:

@reviewed 2022-02-28

In this guide, we learn about Angular HTTP Error Handling. Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor.

Suggested Reading: Error Handling in Angular

Table of Contents

  • HttpErrorResponse
  • Catching Errors in HTTP Request
    • Catch Errors in Component
    • Catch Errors in Service
    • Catch error globally using HTTP Interceptor
  • HTTP Error Handling
  • HTTP Error handling example
  • References
  • Summary

HttpErrorResponse

The HttpClient captures the errors and wraps it in the generic HttpErrorResponse, before passing it to our app. The error property of the HttpErrorResponse contains the underlying error object. It also provides additional context about the state of the HTTP layer when the error occurred.

The HTTP errors fall into two categories. The back end server may generate the error and send the error response. Or the client-side code may fail to generate the request and throw the error (ErrorEvent objects).

The server might reject the request for various reasons. Whenever it does it will return the error response with the HTTP Status Codes such as Unauthorized (401), Forbidden (403), Not found (404), internal Server Error (500), etc. The Angular assigns the error response to error property of the HttpErrorResponse.

The client-side code can also generate the error. The error may be due to a network error or an error while executing the HTTP request or an exception thrown in an RxJS operator. These errors produce JavaScript ErrorEvent objects. The Angular assigns the ErrorEvent object to error property of the HttpErrorResponse.

In both the cases, the generic HttpErrorResponse is returned by the HTTP Module. We will inspect the error property to find out the type of Error and handle accordingly.

Catching Errors in HTTP Request

We can catch the HTTP Errors at three different places.

  1. Component
  2. Service
  3. Globally

Catch Errors in Component

Refer to our tutorial on Angular HTTP Get Request. We created a GitHubService, where we made a GET request to the GitHub API to get the list of Repositories. The following is the getRepos() method from the service. We have intentionally changed the URL (uersY) so that it will result in an error.

getRepos(userName: string): Observable<any> {

   return this.http.get(this.baseURL + ‘usersY/’ + userName + ‘/repos’)

}

We subscribe to the httpClient.get method in the component class

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

  public getRepos() {

    this.loading = true;

    this.errorMessage = «»;

    this.githubService.getReposCatchError(this.userName)

      .subscribe(

        (response) => {                           //Next callback

          console.log(‘response received’)

          this.repos = response;

        },

        (error) => {                              //Error callback

          console.error(‘error caught in component’)

          this.errorMessage = error;

          this.loading = false;

          //throw error;   //You can also throw the error to a global error handler

        }

      )

  }

The subscribe method has three callback arguments.

.subscribe(success, error, completed);

The observable invokes the first callback success, when the HTTP request successfully returns a response. The third call back completed is called when the observable finishes without any error.

The second callback error, is invoked when the HTTP Request end in an error. We handle error here by figuring out the type of error and handle it accordingly. It gets the error object which is of type HttpErrorResponse.

        (error) => {                              //Error callback

          console.error(‘error caught in component’)

          this.errorMessage = error;

          this.loading = false;

        }

Catch Errors in Service

We can also catch errors in the service, which makes the HTTP Request using the catchError Operator as shown below. Once you handle the error, you can re-throw it back to the component for further handling.

  getRepos(userName: string): Observable<repos[]> {

    return this.http.get<repos[]>(this.baseURL + ‘usersY/’ + userName + ‘/repos’)

      .pipe(

        catchError((err) => {

          console.log(‘error caught in service’)

          console.error(err);

          //Handle the error here

          return throwError(err);    //Rethrow it back to component

        })

      )

  }

Catch error globally using HTTP Interceptor

The type of error we may encounter vary. But some of those errors are common to every HTTP request. For Example

  1. You are unauthorized to access the API Service,
  2. You are authorized, but forbidden to access a particular resource
  3. The API End Point is invalid or does not exist
  4. Network error
  5. Server down

We can check all these errors in the service or in component, but our app may contain many such service or components. Checking for common errors in each and every method is inefficient and error-prone.

The Right thing to do is to handle only the errors specific to this API call in this component/service and move all the common errors to one single place. This is where we use the HTTP Interceptor.

The HTTP Interceptor is a service, which we create and register it globally at the root module using the Angular Providers. Once defined, it will intercept all the HTTP requests passing through the app. It intercepts when we make the HTTP request and also intercepts when the response arrives. This makes it an ideal place to catch all the common errors and handle it

We create the Interceptor by creating a Global Service class, which implements the HttpInterceptor Interface. Then we will override the intercept method in that service.

The following code shows a simple GlobalHttpInterceptorService

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import {Injectable} from «@angular/core»;

import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest,HttpResponse,HttpErrorResponse} from ‘@angular/common/http’;

import {Observable, of, throwError} from «rxjs»;

import {catchError, map} from ‘rxjs/operators’;

@Injectable()

export class GlobalHttpInterceptorService implements HttpInterceptor {

  constructor(public router: Router) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req).pipe(

      catchError((error) => {

        console.log(‘error is intercept’)

        console.error(error);

        return throwError(error.message);

      })

    )

  }

}

The caching of the Error is done using the catchError RxJS operator. We then re-throw it to the subscriber using the throwError

The catchError is added to the request pipeline using the RxJs pipe operator . When the error occurs in the HTTP Request it is intercepted and invokes the catchError. Inside the catchError you can handle the error and then use throwError to throw it to the service.

We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS. Note that you can provide more than one Interceptor (multi: true).

providers: [

    GitHubService,

    { provide: HTTP_INTERCEPTORS, useClass: GlobalHttpInterceptorService, multi: true  }

]

Next, step is what to do with the errors

The server-side errors return status codes, we can take appropriate actions based on that. For Example for Status code 401 Unauthorized, we can redirect the user to the login page, for 408 Request Timeout, we can retry the operation, etc.

The following example code shows how to check for status codes 401 & 403 and redirect to the login page.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

if (error instanceof HttpErrorResponse) {

    if (error.error instanceof ErrorEvent) {

        console.error(«Error Event»);

    } else {

        console.log(`error status : ${error.status} ${error.statusText}`);

        switch (error.status) {

            case 401:      //login

                this.router.navigateByUrl(«/login»);

                break;

            case 403:     //forbidden

                this.router.navigateByUrl(«/unauthorized»);

                break;

        }

    }

} else {

    console.error(«some thing else happened»);

}

return throwError(error);

For Server errors with status codes 5XX, you can simply ask the user to retry the operation. You can do this by showing an alert box or redirect him to a special page or show the error message at the top of the page bypassing the error message to a special service AlertService.

For other errors, you can simply re-throw it back to the service.

return throwError(error);

You can further handle the error in service or throw it back to the component.

The component must display the error message to the user. You can also throw it back to a global error handler in Angular.

.subscribe(

   (response) => {

      this.repos = response;

   },

   (error) => {

      //Handle the error here

      //If not handled, then throw it

      throw error;

   }

)

HTTP Error handling example

The complete code of this example

app.component.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<h1 class=«heading»><strong>Angular HTTP</strong>Error Example</h1>

<div class=«form-group»>

  <label for=«userName»>GitHub User Name</label>

  <input type=«text» class=«form-control» name=«userName» [(ngModel)]=«userName»>

</div>

<div class=«form-group»>

  <button type=«button» (click)=«getRepos()»>Get Repos</button>

</div>

<div *ngIf=«loading»>loading...</div>

<div *ngIf=«errorMessage» class=«alert alert-warning»>

  <strong>Warning!</strong> {{errorMessage | json}}

</div>

<table class=‘table’>

  <thead>

    <tr>

      <th>ID</th>

      <th>Name</th>

      <th>HTML Url</th>

      <th>description</th>

    </tr>

  </thead>

  <tbody>

    <tr *ngFor=«let repo of repos;»>

      <td>{{repo.id}}</td>

      <td>{{repo.name}}</td>

      <td>{{repo.html_url}}</td>

      <td>{{repo.description}}</td>

    </tr>

  </tbody>

</table>

<pre>{{repos | json}}</pre>

app.component.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

import { Component } from ‘@angular/core’;

import { GitHubService } from ‘./github.service’;

import { repos } from ‘./repos’;

@Component({

  selector: ‘app-root’,

  templateUrl: ‘./app.component.html’,

})

export class AppComponent {

  userName: string = «tektutorialshub»

  repos: repos[];

  loading: boolean = false;

  errorMessage;

  constructor(private githubService: GitHubService) {

  }

  public getRepos() {

    this.loading = true;

    this.errorMessage = «»;

    this.githubService.getReposCatchError(this.userName)

      .subscribe(

        (response) => {                           //Next callback

          console.log(‘response received’)

          this.repos = response;

        },

        (error) => {                              //Error callback

          console.error(‘error caught in component’)

          this.errorMessage = error;

          this.loading = false;

          throw error;

        }

      )

  }

}

github.service.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

import { Injectable } from ‘@angular/core’;

import { HttpClient, HttpParams, HttpHeaders } from ‘@angular/common/http’;

import { Observable, throwError } from ‘rxjs’;

import { map, catchError } from ‘rxjs/operators’;

import { repos } from ‘./repos’;

@Injectable( {providedIn:‘root’})

export class GitHubService {

  baseURL: string = «https://api.github.com/»;

  constructor(private http: HttpClient) {

  }

  //Any Data Type

  getRepos(userName: string): Observable<any> {

    return this.http.get(this.baseURL + ‘usersY/’ + userName + ‘/repos’)

  }

  //With catchError

  getReposCatchError(userName: string): Observable<repos[]> {

    return this.http.get<repos[]>(this.baseURL + ‘usersY/’ + userName + ‘/repos’)

      .pipe(

        catchError((err) => {

          console.log(‘error caught in service’)

          console.error(err);

          return throwError(err);

        })

      )

  }

}

global-http-Interceptor.service.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

import { Injectable } from «@angular/core»;

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from ‘@angular/common/http’;

import { Observable, of, throwError } from «rxjs»;

import { catchError, map } from ‘rxjs/operators’;

import { Router } from ‘@angular/router’;

@Injectable()

export class GlobalHttpInterceptorService implements HttpInterceptor {

  constructor(public router: Router) {

  }

  //1.  No Errors

  intercept1(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req).pipe(

      catchError((error) => {

        console.log(‘error in intercept’)

        console.error(error);

        return throwError(error.message);

      })

    )

  }

  //2. Sending an Invalid Token will generate error

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const token: string = ‘invald token’;

    req = req.clone({ headers: req.headers.set(‘Authorization’, ‘Bearer ‘ + token) });

    return next.handle(req).pipe(

      catchError((error) => {

        console.log(‘error in intercept’)

        console.error(error);

        return throwError(error.message);

      })

    )

  }

  intercept3(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const token: string = ‘invald token’;

    req = req.clone({ headers: req.headers.set(‘Authorization’, ‘Bearer ‘ + token) });

    return next.handle(req).pipe(

      catchError((error) => {

        let handled: boolean = false;

        console.error(error);

        if (error instanceof HttpErrorResponse) {

          if (error.error instanceof ErrorEvent) {

            console.error(«Error Event»);

          } else {

            console.log(`error status : ${error.status} ${error.statusText}`);

            switch (error.status) {

              case 401:      //login

                this.router.navigateByUrl(«/login»);

                console.log(`redirect to login`);

                handled = true;

                break;

              case 403:     //forbidden

                this.router.navigateByUrl(«/login»);

                console.log(`redirect to login`);

                handled = true;

                break;

            }

          }

        }

        else {

          console.error(«Other Errors»);

        }

        if (handled) {

          console.log(‘return back ‘);

          return of(error);

        } else {

          console.log(‘throw error back to to the subscriber’);

          return throwError(error);

        }

      })

    )

  }

}

global-error-handler.service.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import { ErrorHandler, Injectable, Injector } from ‘@angular/core’;

import { HttpErrorResponse } from ‘@angular/common/http’;

import { throwError } from ‘rxjs’;

@Injectable()

export class GlobalErrorHandlerService implements ErrorHandler {

  constructor() {

  }

  handleError(error: Error | HttpErrorResponse) {

    console.log(‘GlobalErrorHandlerService’)

    console.error(error);

  }

}

app.module.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule ,ErrorHandler } from ‘@angular/core’;

import { HttpClientModule,HTTP_INTERCEPTORS} from ‘@angular/common/http’;

import { FormsModule } from ‘@angular/forms’;

import { AppComponent } from ‘./app.component’;

import { GlobalHttpInterceptorService} from ‘./global-http-Interceptor.service’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { GlobalErrorHandlerService } from ‘./global-error-handler.service’;

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    HttpClientModule,

    FormsModule,

    AppRoutingModule

  ],

  providers: [

    { provide: HTTP_INTERCEPTORS,    useClass: GlobalHttpInterceptorService,    multi: true  },

    { provide: ErrorHandler, useClass:GlobalErrorHandlerService}

],

  bootstrap: [AppComponent]

})

export class AppModule { }

app-routing.module.ts

import { NgModule } from ‘@angular/core’;

import { Routes, RouterModule } from ‘@angular/router’;

const routes: Routes = [];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Angular HTTP Error Handling Example

References

HttpErrorResponse

Summary

Using HTTP Interceptors you can catch HTTP Errors and handle it appropriately. Check the HTTP status codes and take appropriate actions like redirecting to the login page, or redirecting to an error page or else throw the error back to the subscriber for further handling of the error.

This post will be a quick practical guide for the Angular HTTP Client module. We will cover how to do HTTP in Angular in general. We will be using the new @angular/common/http module, but a good part of this post is also applicable to the previous @angular/http module.

We will provide some examples of how to use this module to implement some of the most common uses that you will find during development.

Table Of Contents

  • Introduction to the new HTTP Client module
  • Example of an HTTP GET
  • Improved Type Safety
  • HTTP Request Parameters (Immutability-based API)
  • HTTP Headers (Immutability-based API)
  • HTTP PUT, PATCH, POST, DELETE
  • Some REST Guidelines (specific to RESTful JSON) for using the multiple HTTP methods
  • The use of Generics in the new API enabling more type safe code
  • How To Avoid Duplicate HTTP Requests
  • How to do HTTP Requests in Parallel, and combine the Result
  • How to do HTTP Requests in sequence, and use the result of the first request to create the second request
  • How To get the results of two requests made in sequence
  • HTTP error handling
  • HTTP Interceptors
  • Progress Events
  • Summary

Note: The code for this post is also available in this repository, as a running example.

Introduction to the new HTTP module

The multiple versions of the Angular HTTP module all have an RxJS Observable-based API. This means that the multiple calls to the HTTP module will all return an observable, that we need to subscribe to one way or the other.

Here are some key things to bear in mind regarding this particular type of Observables returned by the HTTP module:

  • if we don’t subscribe to these observables, nothing will happen
  • if we subscribe multiple times to these observables, multiple HTTP requests will be triggered (see this post for more details)
  • This particular type of Observables are single-value streams: If the HTTP request is successful, these observables will emit only one value and then complete
  • these observables will emit an error if the HTTP request fails, more on this later

With this in mind, let’s have a look at some of the most common tasks that we will come across using the HTTP library.

Installing the new HTTP module

In order to install the HTTP module, we need to import it in our root module HttpClientModule:

The REST API That we will be Querying

Let’s now start using the HTTP module, and use it to perform a simple HTTP GET. Just as a demo, we will be querying a Firebase database using the built-in REST capabilities of Firebase, and displaying some data directly on the screen.

This is not the most common way to query Firebase, as we usually use AngularFire together with the Firebase SDK, but there is also REST support available.

This is the data that we will be querying:

Firebase Data

As we can see this data is a JSON structure, with no arrays. Everything is structured as a key-pair dictionary. Those funny looking strings are Firebase unique identifiers, they have some great properties (more about them in this post).

Example of an HTTP GET

And here is an example of a small component that queries the database above using an HTTP GET, and displays the data on the screen.

This example is using the HTTP module in a small component, that is displaying a list of courses. Let’s break down this example step-by-step:

  • We are using the new HttpClient client module, and injecting it in the constructor
  • then we are calling the get() method, which is returning an Observable
  • This observable returns an Object directly, so the HTTP library by default assumes that we have queried a JSON API and it internally parses the HTTP response body as JSON
  • usually, we design our APIs so that they always send an object and not an array, to avoid an attack known as JSON Highjacking
  • so we need to convert the object into a list, by taking only the object values
  • We are then mapping the response we got from Firebase into an array, using the lodash values utility method
  • this defines an observable named courses$, which is consumed by the template
  • the async pipe will subscribe to the HTTP observable, and it’s that implicit subscription that triggers the HTTP request

The end result is that the descriptions of all the courses in the database will show up listed on the screen, in a bulleted list.

Improved Type Safety

Notice in the call to get() that we are passing a generic parameter: we are specifying that the result of the get() call will be an Observable of Course[], meaning that this observable emits values which are arrays of courses.

If we don’t specify a type parameter, then the result of the call to get() will be an Observable<Object> instead.

HTTP Request Parameters

The HTTP GET can also receive parameters, that correspond to the parameters in the HTTP url. Let’s take for example the following URL with some pagination parameters:

https://angular-http-guide.firebaseio.com/courses.json?orderBy="$key"&limitToFirst=1

This query will take the same results as before, but this time ordered by the $key property. The first URL parameter that we have in this URL is orderBy, and the second is limitToFirst.

This is is how we would do this query using the Angular HTTP Client:

Notice that we are building the HTTPParams object by chaining successive set() methods. This is because HTTPParams is immutable, and its API methods do not cause object mutation.

Instead, a call to set will return a new HttpParams object containing the new value properties. So this means that the following will NOT work:

If we try to populate our parameters like this, we will not have the expected result. Instead, we would have an empty HTTPParams object, and the two calls to set would have add no effect.

If by some reason we already have the Query parameters string prepared, and would like to create our parameters using it, we can use this alternative syntax:

Equivalent request() API

The GET calls that we saw above can all be rewritten in a more generic API, that also supports the other PUT, POST, DELETE methods. For example, here is how we could write the same request using the request() API:

This syntax is more generic because we are passing in an initial argument which defines the HTTP method that we are using, in this case GET.

If we want to add custom HTTP Headers to our HTTP request, in addition to the headers the browser already attaches automatically we can do so using the HttpHeaders class:

As we can see, HttpHeaders also has an immutable API, and we are passing a configuration object as the second argument of the get() call.

This configuration object only has one property named headers, just like the local const that we defined — so we used the object short-hand creation notation to define the configuration object.

HTTP PUT

Just like in the case of GET, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification such as PUT.

The PUT method should only be used if we want to fully replace the value of a resource. For example, we would use PUT if we want to overwrite a course object with a completely new version of that same course object:

This example method could for example be part of a component class. If we trigger it via a click handler in a button, we would get the following output in the console:

PUT call successful value returned in body 

{courseListIcon: "https://angular-academy.s3.amazonaws.com/main-logo/main-page-logo-small-hat.png", description: "Angular Tutorial For Beginners TEST", iconUrl: "https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners.jpg", longDescription: "...", url: "new-value-for-url"}

The PUT observable is now completed.

So as we can see, the PUT call will replace the whole content of the course path with a new object, even though we usually only want to modify a couple of properties.

Also, the response body of the PUT call will contain the new version of the course object that was created after the upload. In some cases, this might be a lot of data.

HTTP PATCH

Most often than not, instead of providing a completely new version of a resource, what we want to do is to just update a single property. And this is the main use case for the use of the HTTP PATCH method!

For example, here is how we would update only the course description:

This would be the result of calling this PATCH method:

PATCH call successful value returned in body 

{description: "Angular Tutorial For Beginners PATCH TEST"}

The PATCH observable is now completed.

As we can see, the PATCH method returns only the new version of the modified values, that we already sent initially.

This is useful in situations where there is some sort of further server-side modification of the patched values, such as for example via a database trigger or a Firebase rule.

HTTP DELETE

Another frequent operation that we want to do is to trigger a logical delete of some data. This operation can completely wipe the data from our database, or simply mark some data as deleted. This is an example of how we would delete a given course:

This call would trigger the following results in the console:

DELETE call successful value returned in body null
The DELETE observable is now completed.

In the case of Firebase, this completely removes the object from the database, but we can imagine other REST APIs where only a logical delete would occur.

HTTP POST

If the operation that we are trying to do does not fit the description of any of the methods above (GET, PUT, PATCH, DELETE), then we can use the HTTP wildcard modification operation: POST.

This operation is typically used to add new data to the database, although there are many other use cases. For example, this is how we would add a new course to the database using it:

And here the results that show in the console when this POST request gets executed:

POST call successful value returned in body {name: "-KolPZIn25aSYCNJfHK5"}
The POST observable is now completed.

When we use the POST method to create data in the database, we usually want to return the unique identifier of the data that we just created, so that the client can reference that new resource if needed.

Avoid Duplicate HTTP Requests

Depending on how you use the HTTP module, a problem that you might come across is the occurrence of multiple HTTP requests. This is actually the normal behavior of the HTTP observables, but it might be surprising the first time that we see it.

Sometimes we want to create an observable, and then subscribe to it straight away to implement some functionality which is local to the place where we created the observable.

For example, we might want to do some logging at the level of the service where the HTTP observable is being created. Let’s have a look at one example, still in the same component that we created above:

In this example, we are creating an HTTP observable, and we are doing some local subscription to it. Then this observable is assigned to the courses$ member variable, which will then also be subscribed to using the async pipe, via the component template.

This means that there will be two HTTP requests, once per each subscription. In this case, these requests are clearly duplicate as we only wanted the data to be queried from the backend once.

A new RxJs operator

There are several ways to avoid this situation, but there was recently an operator added to RxJs specifically to tackle this use case — the shareReplay operator.

According to the author of the operator Ben Lesh:

This makes shareReplay ideal for handling things like caching AJAX results, as it’s retryable

So let’s apply this new operator, and see the results:

With the shareReplay operator in place, we would no longer fall into the situation where we have accidental multiple HTTP requests.

And this covers the main use cases for doing the most typical read and modification operations, that we would implement while doing a custom REST API.

Let’s now see some other very frequent use cases, plus some more new features of the Angular HTTP client.

How to do HTTP Requests in Parallel, and combine the Result

One way of doing HTTP requests in parallel is to use the RxJs forkjoin operator:

In this example, we are taking HTTP GET observables and combining them to create a new observable.

This new observable will only emit a value when the two GET observables emit their value. The value of the combined observable will be an array containing the multiple results of each GET request.

How to do HTTP Requests in sequence, and use the result of the first request to create the second request

Another more common use case is to do one HTTP request and then use the result of that request to build a second HTTP request. One way of doing this is to use the switchMap operator:

Notice the use of a generic parameter in the call to get(). This is optional and it helps to keep out program more type safe.

If we don’t use the generic type, then the inferred type of the course variable would be Object, but using this parameter the inferred type is now Course, which gives us auto-completion inside the function passed to switchMap.

Let’s then break down how this switchMap HTTP request chain works:

  • we are defining a source HTTP GET request that reads the data of a course
  • once that source observable emits a value, it will trigger the mapping function that will create an inner observable
  • the inner observable is an HTTP PUT observable that will then send the course modifications back to the server
  • the call to switchMap returns a result observable, that we subscribe to
  • it’s the subscription to the result observable that triggers the subscription to the source GET observable
  • the values of the inner observable (that creates a PUT request) are emitted as values of the result observable.

Have a look at this previous post on switchMap, this operator is likely to be helpful in several different use cases (not only this one).

For example, we can also use it in this other closely related use case.

How To get the results of two HTTP requests made in sequence

In the previous case, we used switchMap to chain two HTTP requests together, creating one request based on the results of the first request.

But the result observable did not have the data of the first request, instead it only had access to the data of the second HTTP request.

If we would like to have both the data of the first HTTP request and deliver it together with the data of the second request, we could use a selector function (notice the second argument passed to switchMap):

The emitted values of the outer result observable with then become an array that contains the two value emitted by each HTTP request in the chain.

Notice that selector functions are not unique to the switchMap operator, they can be used in many other operators.

Also, in these examples, we have used switchMapto chain two HTTP calls, but we could continue calling switchMapon the result observable and keep chaining more calls.

HTTP Error Handling

One of the biggest advantages of RxJs is the built-in error handling functionality, which is hard to get right while doing asynchronous programming.

There is support for many common error handling use cases, but in the case of HTTP requests here is a very common functionality for error handling:

  • we define an HTTP observable, that then emits an error
  • in response, we want to show an error message to the user
  • then we want to still emit some sort of default value for the HTTP stream so that the screens consuming the data still display something useful to the user

This is how we would implement this use case using the RxJs catch operator:

To understand this example, let’s have a look first at the console output:

Error catched 

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/simulate-error", ok: false, … }

Value emitted successfully {description: "Error Value Emitted"}
HTTP Observable completed...

Based on this output, here is what happened in this scenario:

  • The HTTP call occurred and an error was thrown in our test server
  • the catch operator caught the exception, and executed the error handling function
  • inside that function, we could have for example shown the error to the user
  • then the error handling function returns an observable built using the Observable.of() operator
  • This operator creates one observable that only emits one value (the object passed to Observable.of()), and then it completes
  • this returned observable gets subscribed to, and its values start to get emitted by the results observable, so the default value gets emitted
  • the error observable completes, and so the result observable also completes

Notice that by using the catch operator, the error handling function of the result observable would never get called, because the error thrown by the HTTP observable was caught by the catch operator.

HTTP Interceptors

A new feature available in the new HTTP client is HTTP Interceptors. An HTTP Interceptor allows us to add some generic functionality to all our HTTP requests in only one place.

Interceptors are ideal for cross-cutting concerns like for example adding an authentication token header transparently to all the requests made by the HTTP client.

This is an example of how we could implement such an authentication interceptor:

Let’s then break down the implementation of this interceptor:

  • this is a normal Angular injectable service, and we can inject any other services via the constructor
  • in this case, we are injecting a global singleton authentication service, that has access to the authentication token
  • the interceptmethod takes two arguments: the request being intercepted, and the next handler
  • the next.handle method needs to be called to continue the interceptor chain, and for the HTTP request to be made
  • the next.handle method returns an observable, and this is then returned by the intercept method
  • this API is similar to middleware libraries such as express
  • the request object is immutable, so if we want to modify the request for example to add a header, we need to clone it
  • the headers object is also immutable, so as we saw before we need to clone it and create a modified copy of it, for example using (headers.set())
  • The cloned request will now have the new HTTP header X-CustomAuthHeader
  • The cloned and modified HTTP request is then returned to the middleware chain, and the resulting HTTP call will have the new header included

In order to activate this interceptor and apply it to any HTTP request made using the HTTP client, we need to configure it in our application module by adding it to the HTTP_INTERCEPTORS multi-provider:

Progress HTTP Events

Another new use case that is supported by the HTTP client is Progress events. To receive these events, we create our HTTP request manually in the following way:

This is the console output for this example:

Upload progress event Object {type: 1, loaded: 2, total: 2}
Download progress event Object {type: 3, loaded: 31, total: 31}
Response Received... Object {description: "POST Response"}

By creating the request like this, we are receiving all the following HTTP events:

  • an initial upload event when the request gets fully sent to the server
  • a download event, for when the reply arrives from the server
  • a response event, containing the body of the server response

Summary

The new Angular HTTP Client is a great evolution when compared to the previous HTTP client: it’s more user-friendly and helps to improve the type safety of our code.

It also supports several extra use cases: for example interceptors and progress events.

This new HTTP client will exist side-by-side with the previous HTTP module, to allow an easier migration.

I hope that this post helps in getting started with the new HTTP client, if you have some questions please let me know in the comments below and I will get back to you.

To get notified when more posts like this come out, I invite you to subscribe to our newsletter:

And if you would like to know about more advanced Angular Core features, we recommend checking the Angular Core Deep Dive course, where the HTTP Client is covered in much more detail.

If you are just getting started learning Angular, have a look at the Angular for Beginners Course:

Have also a look also at other popular posts that you might find interesting:

  • Getting Started With Angular — Development Environment Best Practices With Yarn, the Angular CLI, Setup an IDE
  • Why a Single Page Application, What are the Benefits ? What is a SPA ?
  • Angular Smart Components vs Presentation Components: What’s the Difference, When to Use Each and Why?
  • Angular Router — How To Build a Navigation Menu with Bootstrap 4 and Nested Routes
  • Angular Router — Extended Guided Tour, Avoid Common Pitfalls
  • Angular Components — The Fundamentals
  • How to build Angular apps using Observable Data Services — Pitfalls to avoid
  • Introduction to Angular Forms — Template Driven vs Model Driven
  • Angular ngFor — Learn all Features including trackBy, why is it not only for Arrays ?
  • Angular Universal In Practice — How to build SEO Friendly Single Page Apps with Angular
  • How does Angular Change Detection Really Work ?

Input Validation is a big topic when it comes to forms. And even more in those large, enterprisey apps, where validation can become really crazy. Now, Angular forms of course provide different mechanisms for handling validation out of the box. However, in this article I won’t go into those details, I will rather show you a possible strategy for visualizing server side validation errors.

Before starting straight away, we can basically have these types of validation:

  • client-side — they prevent you even from submitting the form itself. The simplest for sure being the required validator, or others like checking the max length etc.
  • client-side async — typical use case: checking for the availability of the username. By using an async validator, we can call a function on the server via an API to verify whether the user provided value (in this case the username) has not already been taken. Aside from the difference that we call a server API, the behavior is quite similar. Unless the validator is satisfied, we won’t be able to submit our form.

Sometimes however, we have to submit the form to be able to perform more cross-cutting validation logic. We might need to take the data combine it with other data (from the DB) we only have available on the server side, before ultimately then returning either a success status or fail due to “validation errors”. Such validation errors can then be targeted to a single field (i.e. the username field) or even the entire entity (or user model).

TL;DR

Might want to watch the according Egghead.io lesson then 😉…

HTTP and Status Codes

In modern APIs, whenever we send data to the server and it gets processed successfully, an HTTP 200 response is being sent back to confirm the success. We might even get the data back in the response body, containing additional fields that might have been calculated on the server side. A classic example: the primary key property (usually) id might have been populated on the server side.

Similarly, when something goes terribly wrong, we get an HTTP 500. That’s usually a server error, where the user cannot really do something about it, in terms of modifying the submitted data. It’s usually due to a server outage, configuration or even programming issue.

Aside from a HTTP 500 we might also have a different error scenario, one that depends on the submitted data. Let’s take the “username” example. I know we could easily solve this via an async validator, but let’s assume for now we have to submit the form first and it will be evaluated on the server side. Now if the username is already taken, the server has to communicate that somehow to the client s.t. that one in turn can communicate it to the user and ask him/her to change it.

One might now be tempted to return a HTTP 200 and within the response body provide some information that illustrates the issue. I’ve seen people do something like

// DON'T
// positive response (HTTP 200)
{
  status: 'OK',
  data: {
    ...
  }
}
// DON'T
// negative response (still HTTP 200)
{
  status: 'ERROR',
  errors: {
    ...
  }
}

You can see how the status field in the response is being used to determine whether the request was successful or not. Such an approach is discouraged however. While the structuring of the data in the response body is totally fine (and up to you, even placing the status property), don’t use status fields for determining whether the request is a success or failure. Rather make use the HTTP status code instead!

Communicate validation errors via HTTP

What status code should we use for validation errors? Is it a 500 (server error)? 400 (bad request)? 500 is more like a server side issue, so that’s probably “wrong”. Let’s check 400 - Bad Request:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). https://tools.ietf.org/html/rfc7231#section-6.5.1

That looks better. However “malformed request syntax” and “invalid request message framing” doesn’t quite match it.

I’m usually using 422 - Unprocessable Entity instead. The definition says the following:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions. https://tools.ietf.org/html/rfc4918#section-11.2

I think it best matches our needs. Having defined the status code, we need to determine how to best transport the information back to the client? Well, here it really depends on the type of information you have. If we’re able to directly associate the error to a form input property, the response could look as follows:

// HTTP 422 body
{
  errors: {
    "username": "The username is already taken"
  }
}

(Note, this is just an example. The choice of using an object rather than an array here is just mine, you can totally define this response by yourself)

Visualizing server side validation errors

We now know the HTTP status and the transport format. What’s left is how to map this onto the client-form, which isn’t too difficult after all. The strategy is the following:

  • check whether the HTTP status is 422
  • for each entry in the errors object, try to match a form field and invalidate it

Let’s implement it. Consider our form to be as simple as the following:

<form ...>
  <mat-form-field>
    <input matInput placeholder="Username" formControlName="username" required>
    <mat-error *ngIf="form.get('username').errors?.required">Username is required</mat-error>
  </mat-form-field>
</form>

As you can see there is a required validator and the according <mat-error> (I’m using Angular Material here) that’s responsible for visualizing the error. The required fires immediately, and won’t let us submit the form unless it is valid.

Validation error placeholder for server validation errors

In order to be able to visualize the server-side error messages, we also need a placeholder for visualizing the error message:

<form ...>
  <mat-form-field>
    <input matInput placeholder="Username" formControlName="username" required>
    <mat-error *ngIf="form.get('username').errors?.required">Username is required</mat-error>
    <!-- server-side validation errors -->
    <mat-error *ngIf="form.get('username').errors?.serverError">
      {{ form.get('username').errors?.serverError }}
    </mat-error>
  </mat-form-field>
</form>

As you can see, whenever the username field has errors of type serverError, this new validation error message gets shown and visualizes the text inside the ...errors.serverError property.

Parsing the error and activating the validation message

The part that’s missing is to parse the error. Assume we have a personService that sends the form value back to the server via some HTTP API. In the subscribe, we implement the error callback and check for an HttpErrorResponse as well as our 422 status code.

this.personService.save(value)
  .pipe(
    ...
  )
  .subscribe(x => {
    console.log('Successfully saved person', x);
  }, err => {
    if (err instanceof HttpErrorResponse) {
      const errorMessages = new Array<{ propName: string; errors: string }>();

      if (err.status === 422) {
        // TODO: extract errors here and match onto the form
      }
    }
  })

In such case, we can now parse the error messages based on the response structure we defined earlier. Whenever we get a matching form field, we activate the serverError validation message using the setErrors(..) function of the FormControl:

...
if(err.status === 422) {
  Object.keys(validationErrors).forEach(prop => {
    const formControl = this.form.get(prop);
    if (formControl) {
      // activate the error message
      formControl.setErrors({
        serverError: validationErrors[prop]
      });
    }
  });
}

What about unmatched errors?

For simplicity reasons, I didn’t implement any fallback mechanism here, but you definitely should! There might be situations where you cannot find any matching form field, simply because the property is not shown, the field might be hidden to the user etc. For such scenarios, it is considered good practice to visualize an error notification to the user with all those error messages.

In general it is a good usability practice to show all of the error messages in some type of alert/notification, in addition to trying to match them onto the form directly.

Running Stackblitz Example

Finally, here’s a running Stackblitz example, made with ❤️ for you to play around with 😉. Note, since I don’t have an HTTP server on Stackblitz, I simulate the HTTP calls/responses with some RxJS and delays 😅

Conclusion and Considerations

Here are some final considerations. First of all, this approach definitely requires some “coupling” between the client form and the server response model as the properties obviously have to match. This is something that might not always be the case, whether it’s due to the usage of DTOs (Data Transfer Objects) that get remapped onto client-side entities or for whatever reason. In such cases, applying such strategy gets more difficult, as also the error message would have to be re-mapped accordingly. It is possible but requires some more manual work.

Furthermore, since the server returns the error messages, they have to be localized in the user language. That requires that the language on the client and server side is synced. It’s not necessary to keep a session (which I’d avoid if possible), but you could simply send the user language along as a HTTP header (for instance).
Alternatively, just return some “error code” that gets interpreted and mapped to some localized message on the client. Whatever fits you best 😃

Have a better solution? This is definitely not a golden hammer! I’d love to hear about it!


Questions? Thoughts? Hit me up on Twitter

Понравилась статья? Поделить с друзьями:
  • Android studio setup unable to elevate error 1812
  • Android studio error log
  • An unknown error has occurred please wait a minute or so before trying again
  • An unknown error has occurred heroes 3
  • An internal error has occurred print and inspect the error details for more information