CRUD Operations with Angular, Node.js, Express, SQL Server

 

Step-by-Step Guide to CRUD Operations with Angular, Node.js, Express, and XAMPP SQL Server

Introduction:

Are you an Angular developer looking to build a full-stack application with CRUD (Create, Read, Update, Delete) operations? This article will guide you through the process of integrating Angular with Node.js, Express, and a SQL Server database hosted on XAMPP. By the end of this tutorial, you'll have a fully functional CRUD application that you can showcase in your portfolio or use as a foundation for more complex projects.

CRUD Operations with Angular, Node.js, Express, and XAMPP SQL Server



Why Use Angular, Node.js, Express, and XAMPP SQL Server?

  • Angular: A powerful front-end framework for building dynamic, single-page applications (SPAs).
    Node.js & Express: A robust back-end runtime and framework for building scalable and efficient APIs.
    XAMPP SQL Server: A local server environment that includes MySQL, making it easy to manage your database locally.
    Combining these technologies allows you to create a seamless full-stack application with a responsive front-end, a scalable back-end, and a reliable database.


Step 1: Set Up the SQL Server Database in XAMPP

  1. Install XAMPP: Download and install XAMPP from the official website.

  2. Start Apache and MySQL: Open the XAMPP Control Panel and start the Apache and MySQL services.

  3. Create a Database:

    • Open phpMyAdmin (usually accessible at http://localhost/phpmyadmin).

    • Create a new database (e.g., crud_app).

    • Add a table (e.g., users) with columns like idnameemailand password.


Example SQL for creating a users table:


CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(100) NOT NULL
);


Step 2: Create a Node.js and Express Back-End
1.Initialize a Node.js Project:
  • Create a new folder for your project (e.g., crud-backend).
  • Run npm init -y to initialize a Node.js project.
  • Install required dependencies:
         >   npm install express mysql body-parser cors


2.Set Up the Express Server:
Create an index.js file and set up a basic Express server:



const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(cors());

// MySQL Connection
  const db = mysql.createConnection({
     host: ' localhost',
    user: 'root',
    password: '',
    database: 'crud_app'
});

db.connect((err) => {
    if (err) throw err;
    console.log('MySQL Connected...');
});

// Routes
app.get('/api/users', (req, res) => {
    let sql = 'SELECT * FROM users';
    db.query(sql, (err, results) => {
        if (err) throw err;
        res.send(results);
    });
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});



3.Add CRUD Endpoints:


Add routes for creating, reading, updating, and deleting users. For example:




// Create User
app.post('/api/users', (req, res) => {
  let sql = 'INSERT INTO users SET ?';
  let user = req.body;
  db.query(sql, user, (err, result) => {
      if (err) throw err;
      res.send('User added...');
  });
});

// Update User
app.put('/api/users/:id', (req, res) => {
  let sql = `UPDATE users SET ? WHERE id = ${req.params.id}`;
  let user = req.body;
  db.query(sql, user, (err, result) => {
      if (err) throw err;
      res.send('User updated...');
  });
});

// Delete User
app.delete('/api/users/:id', (req, res) => {
  let sql = `DELETE FROM users WHERE id = ${req.params.id}`;
  db.query(sql, (err, result) => {
      if (err) throw err;
      res.send('User deleted...');
  });
});


4.Test the API:

Use Postman to test your CRUD endpoints (GETPOSTPUTDELETE).

Step 3: Create an Angular Front-End

  1. Generate a New Angular Project:

    • Run ng new crud-frontend to create a new Angular project.

    • Navigate to the project folder: cd crud-frontend.

  2. Set Up Angular Services:

    • Generate a service to handle HTTP requests:

         > ng generate service api

Update the api.service.ts file:



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

@Injectable({
    providedIn: 'root'
)
export class ApiService {
    private baseUrl = 'http://localhost:3000/api';

    constructor(private http: HttpClient) { }

    getUsers() {
        return this.http.get(`${this.baseUrl}/users`);
    }

    createUser(user: any) {
        return this.http.post(`${this.baseUrl}/users`, user);
    }

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

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






3.Create Angular Components:

  • Generate components for listing, adding, updating, and deleting users:



ng generate component user-list
ng generate component user-form



4.Update the user-list.component.ts File:


import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
    selector: 'app-user-list',
    templateUrl: './user-list.component.html',
    styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
    users: any[] = [];

    constructor(private apiService: ApiService) { }

    ngOnInit(): void {
        this.apiService.getUsers().subscribe((data: any) => {
            this.users = data;
        });
    }

    deleteUser(id: number) {
        this.apiService.deleteUser(id).subscribe(() => {
            this.users = this.users.filter(user => user.id !== id);
        });
    }
}

5.Update the user-list.component.html File:



<table>
    <tr *ngFor="let user of users">
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
        <td>
            <button (click)="deleteUser(user.id)">Delete</button>
        </td>
    </tr>
</table>


Step 4: Connect the Front-End and Back-End

  1. 1.Run the Back-End Server:
    Start your Node.js server: node index.js.
    2.Run the Angular Application:
    Start the Angular development server: ng serve.
    3.Test the Application:
    Open your browser and navigate to http://localhost:4200.
    Verify that you can perform CRUD operations seamlessly.

Conclusion:

By following this step-by-step guide, you've successfully built a full-stack CRUD application using Angular, Node.js, Express, and XAMPP SQL Server. This project demonstrates your ability to integrate front-end and back-end technologies, making it a valuable addition to your portfolio.

SEO Keywords: Angular CRUD operations, Node.js Express SQL Server, Angular Node.js tutorial, XAMPP SQL Server CRUD, full-stack Angular application, Angular developer guide, CRUD operations step-by-step.

Read more.




0 Comments