Angular 2 Service Example – Javascript

In this tutorial, we will be creating an application that is able to consume a remote REST API and list countries by region. Looking for TypeScript version?

Folder Structure

How about download the source code and check?

Angular 2 Service Example javascript folder structure


In order to use http, we need to add HTTP_PROVIDERS  to the injector. This is done via the second parameter of the bootstrap function.


This is our main component – AppComponent, which has CountryService  injected. Below is also how we call our service method and retrieve data from http response. We will also display an error text if the API returns any error.


This is the template of AppComponent. It has a search form and also a section to show the search result.


Here is the CountryService . In the service method getCountriesByRegion , we use http.get to retrieve data from REST API and convert the response into json  before passing it to further downstream in this example.



Run the example, type in “oceania” and click on “Search”, you should get the same result as below, unless the remote API is broken. The source code is available for download.

Angular 2 Service example javascript result



Wayne Hong

Passionate Java full stack developer.