You are on page 1of 10

Angular | Http

Angular

Http
pg. 1
Angular | Http

Introduction
The Angular HttpClient simplified the client HTTP API on the XMLHttpRequest
interface exposed by browsers. Additional benefits of the HttpClient include
testability features, typed request and response objects, request and response
interception, Observable APIs, and streamlined error handling.
Table 1. Putting Http in Context

Question Answer
What are they? HTTP requests sent by the browser on behalf of the application.
These HTTP requests are asynchronous. The term asynchronous
refers to the fact that the application continues to operate
while the browser is waiting for the server to respond.
Why are they useful? Asynchronous HTTP requests allow Angular applications to
interact with web services so that persistent data can be loaded
into the application and changes can be sent to the server and
saved.
How are they used? Requests are made using the HttpClient class, which is delivered
as a service through dependency injection. This class provides
an Angularfriendly wrapper around the browser’s
XMLHttpRequest feature.
Are there any pitfalls or Using the Angular HTTP feature requires the use of Reactive
limitations? Extensions Observable objects.
Are there any alternatives? You can work directly with the browser’s XMLHttpRequest
object if you prefer, and some applications—those that don’t
need to deal with persistent data—can be written without
making HTTP requests at all.

Setup HttpClientModule
HTTP has been split into a separate module in Angular. In order to make a http
calls in the project we need to add HttpClientModule in imports property of
@NgModule decorator. and now we are ready to inject HttpClient service into
component where you want to make http calls.
pg. 2
Angular | Http
Fig 1. Configuring HttpClientModule

Setting Up the HTTP Request


Inorder to make http calls we need to inject HttpClient class into the
component. The HttpClient class defines a set of methods for making HTTP requests,
each of which uses a different HTTP verbs
Fig 2. Injecting HttpClient in component class

All the HTTP methods available in HttpClient will return Observable<T> we need
to subscribe it in order to process the response.

pg. 3
Angular | Http

Fig 2. Sending request and processing response

Sending the
Request

Processing the Response

Using Types with the HttpClient


All the HTTP methods available in HttpClient are generic methods. We can
specify the return type so that angular will transform the data in the specified type.
Fig 3. Return specific type transformation

Table 2. Putting Pipes in Context

pg. 4
Angular | Http

Sending a request with headers and Query Params


All the HTTP methods available in HttpClient accepts an optional object that is
used to configure the request headers, query params and etc. The configuration
object is used to set the request header using the header property, and the query
parameters using the params property.
Fig 4. Optional Object

Inorder to set headers for a request we need to pass HttpHeaders object for
headers property. The listed methods are aviable in HttpHeaders: has(), get(), keys(),
getAll(), set(), append() and delete(). HttpHeaders object is an immutable object so
we need to use append() method instead of set().

Inorder to set params for a request we need to pass HttpParams object for
headers property. The listed methods are aviable in HttpParams: has(), get(), keys(),
getAll(), set(), append() and delete(). HttpParams object is an immutable object so
we need to use append() method instead of set().

pg. 5
Angular | Http

Interceptors
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. Interceptors can be used in a number of ways in an application.
– Modify the url ( modify http:// request to https:// )
– Set request headers in HTTP calls like Content-Type or send any custom
headers.
– Authenticate HTTP calls by setting Security tokens
– Show Spin Loaders/ Progress Bars as HTTPS calls are in progress.
– Handle Errors in HTTP calls at one place
– Show Response messages using Notifications/ Toasts
– Retry the request in case of request failure or redirect to error pages.
– Caching: Interceptors can handle requests by themselves, without
forwarding to next.handle(), we can use it for caching requests.

Implementing and provide an Interceptor


Below steps to be followed in order to create an interceptor.
1. Create a class that implements HttpInterceptor interface
2. Implement intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> and provide implementation.

3. Interceptors are dependies of the HttpClient class. So we need to add


dependency in providers property of @NgModule
pg. 6
Angular | Http
Fig 5. Add dependency of HttpClient

Typically an interceptor will transform the outgoing request before returning


next.handle(req). An interceptor may choose to transform the response event stream
as well, by applying additional Rx operators on the stream returned by next.handle().
Fig 6. Capturing the response.

pg. 7
Angular | Http

Handling Errors in Http


The RxJs subscribe call will take three optional arguments:
1. A success handler function, which is called each time that the stream
emits a value
2. An error handler function, that gets called only if an error occurs. This
handler receives the error itself
3. A completion handler function, that gets called only if the stream
completes
Fig 7. Subscribe call arguments.

Limitations of the subscribe error handler


Handling errors using the subscribe call is sometimes all that we need, but this
error handling approach is limited. Using this approach, we cannot, for example,
recover from the error or emit an alternative fallback value that replaces the value
that we were expecting from the backend.
The best way to transform error messages is to use the catchError and
throwError methods.
– The catchError method is used with the pipe method to receive any errors
that occur within an Observable sequence.

pg. 8
Angular | Http

– The throwError method is used to create a new Observable that just contains
the error.
Fig 7. Transform error message.

Once error messages are transformed then it ready to subscribe again so that we
can process the error messages.

HTTP Interceptor to catch errors


As interceptors intercepts when we make the HTTP request and also intercepts
when the response arrives. This makes it ideal place to catch all the common errors
and handle it.
The HttpClient captures the errors and wraps it in the generic HttpErrorResponse,
before passing it to the catchError. The error property of the HttpErrorResponse
contains the underlying error object. It also provides additional context about the state
of HTTP layer when the error occurred.
The errors falls 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).

pg. 9
Angular | Http

Fig 8. ErrorInterceptor sample

pg. 10

You might also like