DEV Community

Cover image for Requests in Angular: Simplified
Burhanuddin Mustafa Lakdawala
Burhanuddin Mustafa Lakdawala

Posted on • Originally published at Medium on

Requests in Angular: Simplified

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
Enter fullscreen mode Exit fullscreen mode

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:

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.

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

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

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.

obj.set('key', 'value')       // will NOT modify object
obj = obj.set('key', 'value') // will modify object
Enter fullscreen mode Exit fullscreen mode

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:

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.

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 or Medium. Feedback is appreciated.

Top comments (0)