Building a CRUD Application with Angular and JSON Server REST API

Posted by








Angular CRUD with JSON Server REST API

Angular CRUD with JSON Server REST API

In this article, we will discuss how to create a basic CRUD (Create, Read, Update, Delete) application using Angular and JSON Server as the REST API.

Setting up the project

First, we need to create a new Angular project using the Angular CLI.

      
        $ ng new angular-crud
        $ cd angular-crud
      
    

Next, we’ll install JSON Server using npm.

      
        $ npm install -g json-server
      
    

Creating a REST API with JSON Server

We’ll create a simple JSON file to use as our database. Let’s create a file called db.json and add some sample data.

      
        {
          "users": [
            { "id": 1, "name": "John Doe", "email": "john@example.com" },
            { "id": 2, "name": "Jane Smith", "email": "jane@example.com" }
          ]
        }
      
    

Now, we can start the JSON Server and point it to our db.json file.

      
        $ json-server --watch db.json
      
    

Creating the Angular application

We’ll use Angular CLI to generate the necessary components for our CRUD application.

      
        $ ng generate component user-list
        $ ng generate component user-details
        $ ng generate component user-create
        $ ng generate component user-update
      
    

Implementing CRUD operations

Now, we’ll implement the CRUD operations in our Angular application using HttpClient to make requests to the JSON Server API.

We’ll create a UserService to handle all the HTTP requests for user data.

      
        // user.service.ts
        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';

        @Injectable({
          providedIn: 'root'
        })
        export class UserService {
          apiUrl = 'http://localhost:3000/users';

          constructor(private http: HttpClient) {}

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

          getUser(id: number) {
            return this.http.get(`${this.apiUrl}/${id}`);
          }

          createUser(user: any) {
            return this.http.post(this.apiUrl, user);
          }

          updateUser(id: number, user: any) {
            return this.http.put(`${this.apiUrl}/${id}`, user);
          }

          deleteUser(id: number) {
            return this.http.delete(`${this.apiUrl}/${id}`);
          }
        }
      
    

Conclusion

In this article, we’ve learned how to create a basic CRUD application using Angular and JSON Server as the REST API. We’ve implemented all the CRUD operations and used HttpClient to make requests to the API. This is a simple example, but it can serve as a foundation for more complex applications.