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

boot.js

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.

app.component.js

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.

app.component.tpl.html

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

country.service.js

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.

index.html

Result

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

Resources


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.