Working with headers

We mentioned the   HttpRequest   classes while introducing the HttpClient class. On a regular basis, you will not need to make use of low-level classes, mostly because of the shortcut methods provided by the HttpClient class abstract and the need to declare the HTTP verb in use (GET, POST, and so on) and the URL you want to consume. With that being said, you will sometimes want to introduce special HTTP headers in your requests or append query string parameters automatically to each request, for argument's sake. That is why these classes can become quite handy in certain scenarios. Think of a use case where you want to add an authentication token to each request in order to prevent unauthorized users from reading data from one of your API endpoints.

In the following example, we read an authentication token and append it as a header to our request to a data service. Contrary to our example, we will inject the options hash object straight into the HttpRequest constructor, skipping the step of creating an object instance. Angular provides a wrapper class for defining custom headers as well, and we will take advantage of it in this scenario. Let's suppose we do have an API that expects all requests to include a custom header named Authorization, attaching the authToken that is received when logging into the system, which is then persisted in the browser's local storage layer, for instance:

const authToken = window.localStorage.getItem('auth_token');

let headers = new HttpHeaders();
headers.append('Authorization', `Token ${authToken}`);
let request = new HttpRequest('products.json', { headers: headers });

let authRequest = http.request(request);

Again, we would like to note that apart from this scenario, you will seldom need to create custom request configurations, unless you want to delegate the creation of request configurations in a factory class or method and reuse the same Http wrapper all the time. Angular gives you all the flexibility to go as far as you wish when abstracting your applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset