In this post we are going to create an Angular 2 application from scratch, the target of this post is to explain the process to create a service and use an API to get the data from that, where we will also see, how to handle the response of the API, preview the response on the view and handle the exceptions if any found in the API call.

Let’s start with the process: Just clone this quickstart AngularJs 2 repo

we will work over this application, don’t worry we’ll remove everything else that is not necessary for this application.

after cloning the same run ​​ `​npm install` it will install all the required dependencies to run the application, now run `npm start` this will run the application on the default port …:3000 and you will see Hello Angular. Hurray now we are ready to work over it.

We will be using the github API to interact with and get data: here it is.

Hope you already opened the cloned project in your favorite editor, in my case it is VS Code. Just head to the src -> app folder in the application, here you will see app.component this is the already created component in the cloned project. I assume you are already aware about the basics of AngularJs 2 like, components, basic TypeScript etc.

Let’s start coding: Create a new service under app folder for AppComponent, so just right click on app folder and create a new file name: data.service.ts.

For now i have created a file “trainingData.json” and pasted the data that came from the github api, and giving the path of this data file in my http get call.

here we have created the data service that is hitting the http request to get the data from that api, and we are catching the error there as well, why we doing this is because if our api doesn’t respond as expected we will catch the error there and our view will not distort at all.