Requests in Angular: Simplified
Tags: angular, typescript, webdev, beginners
Published: 2021-05-18 23:04:04

---
title: Requests in Angular: Simplified
published: true
description: Learn to implement simple requests in Angular using Best Practices
date: 2019-05-19 10:57:45 UTC
tags: angular,typescript,webdev,beginner
canonical_url: https://medium.com/@burlak/requests-in-angular-simplified-c9666f1cd637
cover_image: https://cdn-images-1.medium.com/max/4000/0*-xzLqFgXLhBnJJuM
series: Requests in Angular
---

[//]: # (![](https://cdn-images-1.medium.com/max/1024/0*-xzLqFgXLhBnJJuM)<figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>)

When developing an Angular application, there will certainly come a time when you would want to access online resources. The **_Observable_** provides a simple, yet powerful, way of accessing and programming around delayed resources, and can be further manipulated using **_RxJS operators_**.

This guide is meant to teach you how to implement simple requests in an _Angular_ project and process their responses using Observables.

### The simplest request

Let’s say you want to perform a simple request on an API, how would you go about doing this? You can use the `HttpClient` class to get an Observable that accesses the API.

First, you need a service to initialize the Observable and return it to your components when required. You can create a service using the command:

```
ng generate service SERVICE_NAME
```

Next, we create a function that uses `HttpClient` to return an Observable of the requested resource, and a component that will subscribe to this Observable.

The following code demonstrates an example of simple GET and POST requests where we `console.log()` all the output we get:

{% gist https://gist.github.com/PyroGenesis/5079654130153b407223fca228f08443 %}

Here we see that when subscribing, we use **3** arrow functions:

1. `responseObj => { }` Code within the curly braces executes when the request is **_successful_**. The responseObj contains the response from the server.
2. `errorObj => { }` Code within the curly braces executes when the request is **_unsuccessful_** (there is an error). The errorObj contains details about the error
3. `() => { }` Code within the curly braces executes at the end of the request, **_regardless of success or failure_**. Its most common use is for clean-up of resources.

### Headers

The server you are sending the request to might need valid headers to perform its operation successfully. You can do so by using the `HttpHeaders` class, passing the headers to it during declaration.

{% gist https://gist.github.com/PyroGenesis/6d1a883b75703c4354103e9762299361 %}

Headers need to be passed in the `headers` property of the `options` argument of the request. You can also add headers to the `HttpHeaders` object independent to its declaration using `.set()` and `.append()` methods like so

```typescript
const headers: new HttpHeaders()
headers = headers.set('Authorization', 'my-new-auth-token');
headers = headers.append('Content-Type', 'application/json');
```

#### Difference between `.set()` and `.append()`

Data can be added using `.set()` or `.append()` methods. However, there is **one** major difference between the two.

- `.set()`: Constructs a new body with a **_new value_** for given key. This means if a key already exists, `set()` will override the existing value with the new one.
- `.append()`: Constructs a new body with an **_appended value_** for given key. This method will push the new value with the existing values as an array if the key exists.

> **Note** : Both methods specify that they construct a new body. Hence assignment is necessary to modify the original object.

```typescript
obj.set('key', 'value')       // will NOT modify object
obj = obj.set('key', 'value') // will modify object
```

### Parameters

If you wish to add parameters to your request, **do not** concatenate them with the URL string. This might lead to an invalid URL due to presence of special characters in the parameters.

Instead use the `HttpParams` class:

{% gist https://gist.github.com/PyroGenesis/b930283fe1316b7ed37ae0387fe40369 %}

The `HttpParams` object can be used to contain all the parameters you want to include in your request, which you can use in the `params` property of the `options` argument of the request.

Parameters can be added to `HttpParams` object using `.set()` or `.append()`. The behavior of these methods is the same as that mentioned earlier.

### Body

In HTTP requests, the **body** is used to contain the bulk of the request data. A `FormData` object is used to send string or file data in key-value pairs, while JSON objects have to be _stringified_ before adding them to the request. This is only applicable to POST and similar requests and is passed as the second argument in `HttpClient` requests.

{% gist https://gist.github.com/PyroGenesis/4a34c8ecc7fb3bc7cc2779ee93c317f1 %}

Similar to headers and parameters, data can be added to the `FormData` object using `.set()` or `.append()`. However, one difference in this case is that these methods **do** modify the original object and hence re-assignment is not necessary.

### Conclusion

You have learnt how to perform simple requests in Angular while incorporating _headers_, _parameters_ and a _body_. You now also know how to subscribe to such requests and process their responses.

_This is the first of my articles on DEV.to. You can expect to read more like this by following me on [DEV.to](https://dev.to/burlak) or [Medium](https://medium.com/@burlak). Feedback is appreciated._