HTTP Requests in Angular
Angular comes with a built-in HTTP client. That’s a difference compared to Vue.js or React, which do not provide such tooling.
In order to use the built-in client, it needs to be imported into your module.
You need to import the
HttpClientModule. With that in place, we can inject the
HTTP client into our classes, kind of similar to how we’d do in
HttpClient has methods corresponding to actual HTTP methods, e.g.:
Each method accepts an options object, which is the last parameter. There, we can set things such as headers, query parameters, etc.
By default, the subscrition returned when inoking an HTTP request, resolves to an object representing the body of the response. In some cases, we might need more data, like response headers or the status code. It can be configured via the options object. Here’s an example:
Angular automatically converts the responses to JS objects. We can tell it not to do it:
It can’t be used iwth generic versions of HTTP client’s methods, it wouldn’t make sense anyway, because the whole point of these generics is to automatically get a typed response.
Interceptors allow us to set up some global action on outgoing HTTP requests
and/or incoming HTTP responses. They work a bit like middleware in ASP.NET Core.
Interceptors are created as services implementing
request argument is generic. If we know the type of the respones, we can
use it here instead of
Here’s how we register interceptors. In the module, we’d do:
What we’re doing above is just the DI. We treat
HTTP_INTERCEPTORS as a placeholder for actual interceptors. Angular’s inner
code asks for
HTTP_INTERCEPTORS and it is given whatever we register.
Intercepting incoming responses uses the same kind of services as shown
previously. This time though, we need to makse use of the fact that the second
parameter of the interceptor returns an
Observable. It is going to notify us
of the lifetime of the request.
event that we get access to is the same kind of event that was mentioned
in Raw Response section. We might want to filter out all the
events that are not of type equal to
Response. The interceptor may modify the
response or do anything else with it.
Instead of using
Observables, we can utilize
Promises, making it possile to
await in our code:
Instead of using
HttpClient in our components directly, it makes more sense to
put that logic into some service. Such a service would work like a kind of
repository for a specific kind of data being fetched.