Using JSON-Server in Angular
Today, we'll be creating a small application using Json-Server, which we can use as a Fake Rest API in our projects. For detailed usage and information, you can review the Json-Server documentation. Using Json-Server, we can start implementing APIs that aren't yet ready in our project from the UI side, or easily see how structures like tables we've built will react to large datasets.
Before starting our project, let's install Json-Server:
`npm install -g json-server`
Let's start by creating a new Angular project:
`ng new fakerestapi`
Then, we create a new file named db.json in the location where our project files are located. In the first scope we open, we write the string expression we will use as the endpoint. In this example, our endpoint is "heroes".
After that, we start defining our data as if we were defining an array.
db.json
From this point, we begin creating our template on the Angular side. We will mostly continue with screenshots; you can access the source code via GitHub. Let's run the "db.json" file we created as a REST service. If we are not in the same path as the "db.json" file, remember to specify the file's path.
json-server —watch db.json
After this command, our Fake service starts running on port 3000 of our localhost. If we want to use a different port, we can use the port parameter. Let's try to access our data using Postman. When we send a GET request directly to the endpoint, we list all our data.
Get All Heroes
If we want to access by ID, we can access the record with ID 1 using localhost:3000/heroes/1. JSON-server provides us with flexibility in many ways. It allows sorting,
filtering, and retrieving records in a pageable format. Let's turn this data we prepared with Angular into a table. Working with type safety is important, so we first create our hero model.
heroes.ts
Let's write the service that will retrieve the data. We're writing the functions that will perform basic CRUD operations.
heroes.service.ts
We define our model within our component. We write the functions that will retrieve and manipulate the data.
heroes.component.ts
Now, let's add our table, the dialog box that will allow us to create new heroes, and the button to perform the delete operation within our component.
When working with UI frameworks, JSON-Server greatly facilitates the learning process. Thanks to JSON-Server's pagination feature, we can learn about structures that require back-end services, such as Lazy Load.
We will also frequently use Primeng, a component library designed for Angular, in our projects. We discussed the use of JSON-Server before moving on to more complex structures with Angular. We will use it frequently in our future applications. In our next article, we will discuss Lazy Load, a structure we frequently use in tables.

Mete AYDIN