Spring Boot - Spring Boot + Angular + MySQL CRUD example

Spring Boot - Spring Boot + Angular + MySQL CRUD example

We are using above EmployeeServices as SpringBoot rest API, we create UI using Angular to display UI.

Create Angular Project

You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.

npm install -g @angular/cli

To create a new workspace and initial starter app.

ng new employee-angular-app

Run the application

ng serve --open

The –open option automatically opens your browser to http://localhost:4200/.If your installation and setup was successful, you should see a page similar to the following.

for generate any thing we need to use ng g c/s

  • g -is for Generate

  • C – is for Component

  • S– is for Service

EmployeeModel - Model class to hold Employee Data

C:\Git\books\Codes\employee-angular-app>ng g class employee
CREATE src/app/employee.spec.ts (162 bytes)
CREATE src/app/employee.ts (26 bytes)

Create Employee Model class with Employee Table Properties

export class Employee {

    id!: number;
    name!: string;
    address!: string;
    salary!: number;

}

EmployeeListComponent - To Display all Employee data

C:\Git\books\Codes\employee-angular-app>ng g c EmployeeList
CREATE src/app/employee-list/employee-list.component.html (To display UI)
CREATE src/app/employee-list/employee-list.component.spec.ts 
CREATE src/app/employee-list/employee-list.component.ts (Logic)
CREATE src/app/employee-list/employee-list.component.css (Stylesheet)
UPDATE src/app/app.module.ts (newly created component is added & imported)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';

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

Above are automatically added after generation of component.

#employee-list.component.html
<h1>
    Employees List Page
</h1>
//employee-list.component.ts	(Default Generated Class)

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-employee-list',		
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

If we place above app-employee-list in main html(app.component.html) it will display data generated by employeelist component.

//app.component.html
<div>
	…. Old code ….
 </div>

<app-employee-list></app-employee-list>

Change code to display sample Employee data

#employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css'],
})
export class EmployeeListComponent implements OnInit {
  //List of emplyee objects created, initilaized to EMpty.
  employeeList!: Employee[];
  constructor() {}
  //Samle Employee Data.
  ngOnInit(): void {
    this.employeeList = [
      {
        id: 101,
        name: 'Satya',
        address: 'Init-data',
        salary: 18000,
      },
      {
        id: 102,
        name: 'RAM',
        address: 'Init-data',
        salary: 11000,
      },
    ];
  }
}
employee-list.component.html
<div class="card">
  <div class="card-body">
    <div class="col-10 mx-auto">
      <h2 class="text-center">Employees List</h2>
      <!-- <p> </p> -->
    </div>
    <br />
    <div class="row">
      <div class="col-10 mx-auto">
        <table id="example" class="table table-striped table-bordered" style="width: 100%">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">Name</th>
              <th scope="col">Address</th>
              <th scope="col">Salary</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>

            <tr *ngFor="let employee of employeeList">
              <td>  </td>
              <td>  </td>
              <td>  </td>
              <td>  </td>
              <td>
                <button class="btn btn-primary"><i class="fas fa-eye"></i> </button> <span>&nbsp;</span>
                <button class="btn btn-warning"><i class="fas fa-edit"></i> </button> <span>&nbsp;</span>
                <button class="btn btn-danger"><i class="fas fa-trash-alt"></i> </button>

              </td>
            </tr>

          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

EmployeeService – To communicate with SpringBoot Services

C:\Git\books\Codes\employee-angular-app>ng g s employee
CREATE src/app/employee.service.spec.ts (367 bytes)
CREATE src/app/employee.service.ts (137 bytes)
//employee.service.ts (Default generated code)
import { Injectable } from '@angular/core';

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

  constructor() { }
}

We need to use HttpClientModule to call Services. We need import that module in app.module.ts

//employee.service.ts (CURD Operations Rest Call)
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs';
import { Employee } from './employee';

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

  private baseURL = "http://localhost:8080/api/v1";

  constructor(private httpClient: HttpClient) { }

  getEmployeesList(): Observable<Employee[]>{
    return this.httpClient.get<Employee[]>(`${this.baseURL}/all`);
  }

  createEmployee(employee: Employee): Observable<Object>{
    return this.httpClient.post(`${this.baseURL}/addEmployee`, employee);
  }

  getEmployeeById(id: number): Observable<Employee>{
    return this.httpClient.get<Employee>(`${this.baseURL}/getEmployee/${id}`);
  }

  updateEmployee(id: number, employee: Employee): Observable<Object>{
    return this.httpClient.put(`${this.baseURL}/updateEmployee/${id}`, employee);
  }

  deleteEmployee(id: number): Observable<Object>{
    return this.httpClient.delete(`${this.baseURL}/deleteEmployee/${id}`);
  }
}

Now call getEmployeesList() method in EmployeeListComponent to get employees data.

// employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';

//1.Imported EmployeeService
import { EmployeeService } from '../employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css'],
})
export class EmployeeListComponent implements OnInit {
  //List of emplyee objects created, initilaized to EMpty.
  employeeList!: Employee[];

  //2. Created EmployeeService Object to call methods
  constructor(private employeeService: EmployeeService) {}

  //3.at the time of initilaizing calling getEmployees
  ngOnInit(): void {
    this.getEmployees();
  }

  //4.Finally, employeeList object contains all empdata coming from SpringBoot
  private getEmployees() {
    this.employeeService.getEmployeesList().subscribe((data) => {
      this.employeeList = data;
    });
  }
}

Angular Routing

app-routing.module.ts (Default generated code)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

we need to configure path for each component like below

import { EmployeeListComponent } from './employee-list/employee-list.component';

const routes: Routes = [
  {: 'all', : EmployeeListComponent}
]; 

Next, in app.component.html – we need to place <route-outlet> to display the content based on path

<!--This is used directly to display all Empoyees
  <app-employee-list></app-employee-list> -->

<!-- Based on Route it will display content -->
<router-outlet></router-outlet>

Similarly, we need to create Components for ADD, UPADATE, DELETE employee

C:\Git\books\Codes\employee-angular-app>ng g c 
CREATE src/app/add-employee/  
CREATE src/app/add-employee/

Complete Code. Github

https://github.com/smlcodes/Books-Sync-Gitlab/tree/main/Codes/employee-angular-app

Ref.

https://github.com/RameshMF/Angular-10-Spring-Boot-CRUD-Full-Stack-App

https://www.youtube.com/watch?v=tLBX9fq813c&list=PLGRDMO4rOGcNzi3CpBWsCdQSzbjdWWy-f