Sitemap
Codez Up

Codez Up

Code the Way Up

Display Table in Angular using JSON Server Rest API

7 min readMay 19, 2019

--

This post is first published on CodezUp.com

Hi Guys,

In this tutorial, we are going to Display Table in Angular using JSON Server Rest API.

JSON Server is a simple project that is build to setup a REST API with CRUD operations fast and efficiently. The project website can be found at https://github.com/typicode/json-server. So, due to these API, one can build project in much simpler approach and it helps to speed up front-end development time.Install JSON Server

Install JSON Server

But before starting the tutorial, make sure that you must install JSON Server. Since, JSON Server is provided as a NPM package. So, the installation of JSON Server can be done by using the npm (Node Package Manager):

npm install -g json-server

Here, -g option is used to install the package globally in our system.

Now, First we have to create a new angular project. Let’s create a new Project named JSONServer using command “ng new JSONServer”. Wait for few minutes so that it build the project successfully. Let me forward the video to save time.

Since for Angular Projects, I am using Visual Code Editor. So, Let’s start the project by typing “code .” in command prompt.

Create db.json file

Before start writing to the project, Create a new JSON File db.json which contains data and can be accessed bt REST API. And the db.json file should be created outside the src folder or along with the package.json file.

This file has a structure consists of Users Object which has 10 records assigned. Each Users Object contains 6 properties : id, firstName, lastName, email, mobile and salary.

Let’s look at the db.json JSON File below :

Now, first go to the src folder under which go to app folder. Open the app.component.html file and delete all the contents from it.

Now let’s create a header of our App named JsonApiTable. Let’s first create a basic layout for table and define header and rows section for table.

Before working on Table, First we need to create a REST Service to access the data from db.json file. So, create a service named RestService below.

ng generate service Rest

After creating Rest Service, go to rest.service.ts file and implement getUsers() method to retrieve all users from json file. For impementing Rest Servive which require URL to access, we first have to inject HTTP Service in our Rest Service. So for injecting HTTP Service inside Rest Service, create private variable as http of HTTPClient in constructor of RestService.

constructor(private http : HttpClient) { }

But before we access HTTP Service, we also have to import it in our app.module.ts file. So first go to app.module.ts file and under imports array, add HttpClientModule to it.

imports: [
BrowserModule,
HttpClientModule
]

Now, As we know that our db.json file contains Users Object and each Object consists of 6 properties. So for accessing them by JSON Server we have to provide url to read that Object Users. The Url for Rest Service to access file is :

url : string = "http://localhost:3000/Users/"

The following HTTP endpoints are created automatically by JSON server:

GET    /Users
GET /Users/{id}
POST /Users
PUT /Users/{id}
PATCH /Users/{id}
DELETE /Users/{id}

As in db.json file, each object has 6 properties. We can’t access the values directly from an object. So, for accessing them, we need to create class named Users with these properties defined. Let’s create Users class and a constructor to assign values to its properties.

Now, implement getUsers() method to retrieve all users from json file. For that we are using HTTP GET request to http://localhost:3000/Users to get all users.

getUsers()
{
return this.http.get(this.url);
}

Since, the GET Request is going to return Users Object in form of array. So, we declare array of class Users[] to get those objects.

As of now, we have done implementing our Custom Rest Service for accessing data from db.json file. Now we need to inject our Custom Rest Service into our project that is injecting our Rest Service inside app.component.ts file.

For injecting Rest Service, we have to declare a private variable restService of type RestService inside the constructor of app.component.ts file. Now variable restService is used to perform each and every method of RestService.

constructor(private rs : RestService) { }

Now, declare headers columns of the table as an array in app.component.ts file. Our headers columns are : User Id, First Name, Last Name, Email, Mobile and Salary.

columns = ["User Id","First Name","Last Name", "Email", "Mobile", "Salary"];

Now also declare index array of headers columns in form the properties are declared or defined in db.json file that is id, firstname, lastname, email, mobile, salary.

index = ["id", "firstName", "lastName", "email", "mobile", "salary"];

After that, caete an empty variable “users” holding array of custom class Users.

users : Users[] = [];

Now, we need to call our getUsers() method that is defined in our Custom Rest Service so that we can show the data in table format.

Since, we require the at the time the project loads intially. So for that we need to call getUsers() method inside ngOnInit() built in method in Angular. Because ngOnInit() is called immediately as the project loads.

Get Codez Up’s stories in your inbox

Join Medium for free to get updates from this writer.

So, call the getUsers() method using restService and subscribe() the Observable or response that we get from JSON Server and add all objects of type Users class in users array.

ngOnInit(): void {
this.restService.getUsers().subscribe
(
(response)=>
{
this.users = response;
},
(error) => console.log(error)
)
}

Since, we have retrieve all records from the db.json file and store them back in users array. Now, let’s move to the file app.component.html file, where we have defined basic layout of our table.

For displaying the users array in form of table, we have to use *ngFor to iterate through each User Object. I have already posted how to create table using ngFor in our previous article. So, let me skip this part and write directly table code in app.component.html file.

<table id="users">
<tr>
<th *ngFor="let col of columns">
{{col}}
</th>
</tr>
<tr *ngFor="let user of users">
<td *ngFor="let col of index">
{{user[col]}}
</td>
</tr>
</table>

Now, we are done with creating table in Angular using JSON Server API.

Let’s start the server using ng serve command or with npm start command and see what we have created. And along with this start our JSON Server also in another command prompt by typing following command:

ng serve  // For starting the Angular Projectjson-server --watch db.json   // For starting the JSON Server

Here, –watch means the server is started in watch mode and which means that it watches or track for file changes and updates to the API accordingly.

Let’s wait for the project to compile successfully. Once it successfully compiles, Go to your Browser and type http://localhost:4200.

As we can see the table is successfully created but it doesn’t seems to good in visualization. Let’s add some css to our table so it looks little better.

For that go to app.component.css file and style your table. For styling table first create an id property of table as “users”, and add css properties using this id.

Let me skip this part and directly add css to file.

Now we have successfully added css and saved all files, it automatically compiles the project in the background.

Let’s check the browser again and now our table seems to be little better.

Angular Project Files Content :

app.component.ts File

<h1>Table using JSON SERVER API</h1>
<hr>
<table id="users">
<tr>
<th *ngFor="let col of columns">
{{col}}
</th>
</tr>
<tr *ngFor="let user of users">
<td *ngFor="let col of index">
{{user[col]}}
</td>
</tr>
</table>

app.component.ts File

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.css File

h1
{
text-align: center;
color: #4CAF50;
}
#users {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}

#users td, #users th {
border: 1px solid #ddd;
padding: 8px;
}

#users tr:nth-child(even){background-color: #f2f2f2;}

#users tr:hover {background-color: #ddd;}

#users th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}

Rest Service API FIle

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Users } from './Users';
@Injectable({
providedIn: 'root'
})
export class RestService {
constructor(private http : HttpClient) { } url : string = "http://localhost:3000/Users/"
getUsers()
{
return this.http.get<Users[]>(this.url);
}
}

Users.ts File

export class Users
{
id:string;
firstname:string;
lastname:string;
email:string;
mobile:string;
salary:string;
constructor(id,firstname, lastname, email, mobile, salary)
{
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.mobile = mobile;
this.salary = salary;
}
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { RestService } from './rest.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [RestService],
bootstrap: [AppComponent]
})
export class AppModule { }

Hope you guys like the tutorial, feel free to drop any comments in the comment section below.

--

--