Updates to Angular 2 that makes coding easier - HTTP Client

 Oct 20, 2016

In this second part in my series of blogs regarding Angular 2 updates, I would like to cover some of the changes made to the HTTP client. Same as in my previous blog, I will look at the version prior to version 2.0.0-rc.6 and what updates this version has as of the writing of this post.

To get the blog started I will cover the use of the HTTP client, this will be of benefit to anyone who haven’t used it before. When the requirement is to fetch information from a server / external source you can make use of the HTTP client within Angular 2 to form requests that can either fetch (GET) or send (POST) this information.

Once data has been retrieved from the server side, by using a HTTP Get request you can either return a Promise object or an Observable object. The former is often used by developers and was commonly used in Angular JS, this promise object represents a value that isn’t necessarily known when the object is created. By creating a promise we can bind handlers to the object so when the eventual success or failure is called then we can invoke actions upon it. As for the latter, called an observable object. In this approach we are essentially creating an object that opens up a continuous channel of communication in which collections of data can be emitted over time, we then subscribe to this observable object to listen to any new data that can be coming through at any time.

In version 2.0.0-rc.6, they have removed the HTTP_PROVIDERS completely. With the previously mentioned changes in mind, it now means that we have to update our code to use HttpModule instead.

To start looking at using the HTTP_PROVIDERS firstly and then we will move on to the HttpModule approach.

The first order of business is to get a hold of the HTTP service that you need to use in order to make calls to the data source, this can be achieved by adding the following to the main.ts file and bootstrapping the service so it can be reused across the entire application.

Once you have the reference to the service, you can then import the HTTP service name into the file where you want to use it. In my case the file will be the Person.Service.ts file (This file will be used to fetch data from a public API). Once the HTTP service is referenced we can then inject the service into our class by using a constructor, this will allow us to use the HTTP requests such as GET and POST.

Up to this point we have the needed references in our application and we have injected the HTTP into our custom made service that will make the requests, now we need to actually call upon the API and fetch some data. To perform this request, we will make a GET request. Making a get requests requires you to use the newly inject HTTP service and use the get method that it implements, the following screenshot represents this.

Finally we need our application to consume the data coming in from the server, this can be achieved by subscribing to the service method we created in the previous step and then populating an object with the response data. This part will be represented in two parts, firstly we will look at the code needed in our app.component.ts file to consume the data.

Furthermore, we will add some HTML to the components view to actually display the data we just received from the service.

With these pieces of code in place you could now have started your application and you should have seen the information being displayed on your page, but remember this is the deprecated way of doing it. We will now look at the updated way of using HTTP requests.

Firstly, the code we specified in the main.ts file has been removed and reverted back to the boilerplate code. The next part was to create a class to represent the object’s information I want to display to the user, I have created a class called Person and it contains the following properties:

  1. Name – store the name of the person
  2. Gender – store the gender of the person
  3. eyeColor – store the colour of the selected person
  4. birthYear – store the year of birth for the selected person

Once we have created the class we can now go and update our app.module file to contain a reference to the HttpModule class that we will use to get a hold of the Http client.

Note lines 4 and line 7, they contain the needed changes. These changes includes the reference to the HttpModule class and adding the same class to the imports array so my application can reuse it.

Next, we create the person.service file that will contain the logic to fetch the data from the API. This service will have multiple import statements and a bit of code to it, but I will go over the code piece by piece.

From line 1 to 5 we have the import statements, they allow us to do the following:

  • Line 1: Make sure our class is marked as Injectable, this is needed if you want it to be a service
  • Line 2: Imports Http and Response, Http will be used to make requests and Response will be used to make an object that holds the data coming back
  • Line 3: Imports the class Person so that we can return an object of this type
  • Line 4: Imports the Observable class so that our response can be returned as an Observable
  • Line 5: Imports the map operator, this will be needed as we will be mapping our data from the response into the person type.

Lines 8 to 16 represents the class logic and this encapsulates the following logic:

  • Line 9: Specifies the constructor so that we can use the http provider to perform a get request
  • Lines 11 – 14: This is a method that returns a generic Observable object and uses the Person object as the type. In this method we perform a get request against our API URL and then we call the mapdata function within the map function to make sure we do the data mapping properly. After the mapping has been done we then returned the mapped observable to the caller
  • Lines 16 – 18: This is the function called mapdata, this has an input argument of type Response called “res” and it returns an object of type Person. In this function we first create an object called “r” and set it equal the JSON represented by the response. We then create an object called “Item” that will contain all the needed mappings that we want to extract from the response object and map it up to the person object, which will then in turn be returned to the caller

The final part to make this application work is to consume the data that the service will return, to do this we will modify the app.component file so it looks like this:

  • Line 1: Contains the import for the component class and the OnInit interface, this interface is used when we want to perform actions when the component initializes
  • Line 2 and 3: contains imports to the Person Service and the Person Class
  • Lines 4 – 16: Contains the metadata needed for the component to be reused by other components, there are a few things here that you need to take note of:
    • The template that defines our HTML
    • The providers array that should contain your service you want to use
  • Lines 17 – 23: Represents the class and the logic of the component
    • Line 18: creates an object to represent the retrieved person
    • Line 19: We use a constructor to inject the service instance to be used by our class
    • Line 20 – 22: the ngOnInit method is required since we have implemented the OnInit interface on this class, we commonly use this method to retrieve information from data sources. In this method we call the service and invoke the method to retrieve the data we want to consume, after calling the method we want to subscribe to the method to see any future changes to the data automatically. Inside of this subscribe method we have an input argument of people, we will set the person object equal to this input value.

Our final result will now look like the following page:

With this result I will conclude my blog on the updates made to Angular in regards to HTTP Calls.

For more information, take a look at our Angular 2 training courses.

How do your Excel skills stack up?   

Test Now  

About the Author:

Auret Swanepoel  

As a recent addition to the New Horizons team, Auret is a highly skilled and qualified IT Technical trainer. He has been a Microsoft Certified Trainer (MCT) since 2008 and has since then, also become a Microsoft Certified Professional (MCP), a Microsoft Certified Technology Specialist (MCTS) and a Microsoft Certified Information Technology Professional (MCITP). With his international experience as a trainer in South Africa, Auret is able to adapt his teaching style to different audiences in the classroom and ensure that students are learning in a positive and collaborative environment.

Read full bio
top
Back to top