Angular http get example

Angular http get example

HttpModule is re-implementation in Angular 4.3 and introduce a new module HttpClientModule. This new module is available in package @angular/common/http. HttpClientModule provides different methods like get, post, put etc to interact with rest services. In this article we will be discussing get method in detail.

Setup a project using Angular CLI

If you don’t have Angular CLI installed on your system yet, use following command to install latest version of Angular CLI.
npm install -g @angular/cli@latest 

Create a new project using Angular CLI using following command.
ng new httpgetexample

Import HttpClientModule to the project

In order to use HttpClientModule, first we need to import it to our application module file. In this case app.module.ts file is our application module. So, import HttpClientModule to the app.module.ts file.

Inject HttpClient Service

Having imported HttpClientModule, we can inject HttpClient to any of our component.

User HttpClient to get JSON data

Using HttpClient get method we can request data from server.

In this example we have created a emp.json file inside asset folder which contains emp data as follow.

After running this example following output is displayed on the browser console.

Type-checking the response

It is best practice to use typed object instead of object without any type checking. The object in browser contains different functions which are not in use. Also we can’t use dot operator on the object to get a specific property like firstName or lastName. To overcome all these problems, Angular provides type checked response.

To support type-checking the response, create a interface which contains some or all properties of the response. In this example create interface Emp as follow.

get method with type-checking to get Emp object.

After running this example following output is displayed on the browser console.

Download full example httpgetexample

Stay tuned for more update !!!

Leave a Reply

Your email address will not be published. Required fields are marked *