Angular 10 HTTP GET Request Example





Hey guys in this post we will discuss how to make HTTP GET requests in Angular 10. We will use Fake REST API to make the GET requests.

Here is the API endpoint: https://jsonplaceholder.typicode.com/users

This API will give the list of users in JSON format. Below is the sample data –

[
   {
		"id": 1,
		"name": "Leanne Graham",
		"username": "Bret",
		"email": "[email protected]",
		"address": {
			"street": "Kulas Light",
			"suite": "Apt. 556",
			"city": "Gwenborough",
			"zipcode": "92998-3874",
			"geo": {
				"lat": "-37.3159",
				"lng": "81.1496"
			}
		},
		"phone": "1-770-736-8031 x56442",
		"website": "hildegard.org",
		"company": {
			"name": "Romaguera-Crona",
			"catchPhrase": "Multi-layered client-server neural-net",
			"bs": "harness real-time e-markets"
		}
	}
 ...
]

Tools to be installed


First, we need to install Nodejs. Head over to nodejs official website https://nodejs.org/en/ and download the latest version. At the time of writing this article, the latest version of Nodejs is 15.5.1

You can verify the version by executing the below command,

node -v

Next, we need to install Angular globally on our machine

npm install -g @angular/cli

This will install angular CLI globally on our machine. You can verify the Angular CLI version by executing the below command,

ng --version

Development Process


let’s look at the development process step by step



Create an Angular Project


First, we will create an Angular 10 project using angular CLI. Open a command prompt and execute the following command

ng new AngularDemo

AngularDemo is the name of the application. This will create angular 10 projects. By default, angular generates the root component which is the App component and it also adds HTML content to the app.component.html. Let’s go and remove all the content.

Create angular service


We will generate the Angular service using Angular CLI and below is the command for that –

ng g s app --skipTests

g stands for generate, s stands for service, --skipTests will not generate spec files

Update Root module


Next, we need to import HttpClientModule to the root module. let’s open app.module.ts file and import the HttpClientModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from "@angular/common/http";

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Update App Service


Next, create a method inside the AppService to make HTTP GET request. let’s open app.service.ts file and add the following code –

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor(private _httpClient: HttpClient) { }

  getUsers() {
    return this._httpClient.get('https://jsonplaceholder.typicode.com/users');
  }
}

Also, we will be injecting the HttpClient to the contructor to make HTTP GET request.

Update app component


Next, inside the app.component.ts file within the ngOnInit() let’s call the service method to get the list of users. Open app.component.ts file and add the following code –



import { Component, OnInit } from '@angular/core';
import { AppService } from "./app.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  
  public users: any = [];

  constructor(private _appService: AppService) {}

  ngOnInit(): void {
    this._appService.getUsers().subscribe(users => {
      this.users = users;
    })
  }
}

First, we need to inject the AppService into the constructor to call the service method. The service method will return an Observable then we will call subscribe() method to get the users. Finally, we will assign the data to the global variable users.

Update App Template


So final step is to update the app component HTML template to display the data in tabular format. We will loop through the data using angular structural directive ngFor and we will use interpolation to access the object. Open app.component.html add the following code

<table border="1">
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Email</th>
    <th>Website</th>
  </tr>
  <tr *ngFor="let user of users">
    <th>{{user.id}}</th>
    <th>{{user.name}}</th>
    <th>{{user.email}}</th>
    <th>{{user.website}}</th>
  </tr>
</table>

Run the app


That’s it now let’s go to the root of the project/folder and run the following command –

ng serve --open

This will run the angular project with the default URL http://localhost:4200





Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply