Angular 2 Service Example – TypeScript

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 this example in javascript?

 

Folder Structure

How about download the source code and check?

Angular 2 service example code structure

boot.ts

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.ts

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 also display error message if the remote API returns 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.ts

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 a result the same as below, unless the remote API is broken. The source code is also available for download.

Angular 2 Service example result

Resources

Angular 2

 


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.
  • Sean

    very nice…
    Regards,

    Sean

    ================

    Checkout the Ultimate Angular 2 Boorstrap App: @ http://ng2.javascriptninja.io

    Source@ https://github.com/born2net/ng2Boilerplate

  • Joe Schmucker

    You are my new hero.

    • Prashant Tahiliani

      How do i run this project

  • Prashant Tahiliani

    How do i run this project..there are no instructions to run the project

  • Prashanth

    Thank you very much.it was very helpful. Its working amazing with url provided in source code.
    However, I am trying to call different url ” http://wingerweb.azurewebsites.net/WingerApp/rest/menuitems/1” and it is giving me bellow error. Can you please help
    Object { _body: error, status: 200, statusText: “Ok”, headers: Object, type: 3, url: null }

    • Wayne Hong

      Hi Prashant, thanks for your comment. Is that the response object you got with that url? the communication looks alright as it returns 200. you might need to check why the body is error. by the way, where did you print that object? if possible, could you please post some code here?

  • Majid Lotfi

    Could you please answer the question :
    How to run this code ?
    Thanks.

    • Wayne Hong

      Hi,

      the easiest way is using Bracket. just download the source code, open the folder using Bracket and then click on the live preview.

      hope this helps.

      Thanks,