Advanced Features of HttpClient Service
Let's explore how we can set the header options and pass parameters in an HTTP request, intercept HTTP requests and responses and listen to HTTP events.
We'll cover the following...
As we have seen, the HttpClient
service makes it easy to call a RESTful API, but there is more we can do with our HttpClient
calls. We’re now going to look at some of the more advanced features to see how we can use them in our Angular applications.
Setting the HttpHeader options
One of the first things we can do is set the header options just before we make an HTTP request.
For example, we may have a request that requires a different set of header options from the other HTTP requests we’re making in a service. Maybe when we are making a post
request, we need to provide a different authentication token from the other HTTP requests we have in service.
To do this, we can use the set()
method of the httpOptions
object to create a new set of options. In our earlier example, we created httpOptions
like this:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'authentication-token' })
};
Here, we’ve created a const
variable with HttpHeader
options that can be used in all our HTTP requests, but if we want to make a new header option, we have to use the set()
method to change the options:
httpOptions.headers = httpOptions.headers.set('Authorization', 'new-auth-token');
This ability to update the header options allows us to easily set them if we need to make a change. If your application uses a temporary authentication token for an initial request and is then returned a new token, we can set the new authentication token using this method.
Pass parameters using HttpParams
Another ...