CRUD Operation In Angular 6 With Web API

CRUD Operation In Angular 6 With Web API

In this article, we’ll learn CRUD operation using Angular 6 application with web API, step by step from scratch with sample example. We’ll generate our Angular 6 sample application using angular CLI. then we’ll create an employee management application where there will be a login screen for an admin and after login.

The employee can perform CRUD operations such as read, create, update and delete employee with the help of sample REST API exposed using HttpClientModule.

We’ll also be using RouterModule to have routing enabled. Also, in the end, we will be adding material designing with our Angular 6 app.

Prerequisite

It requires the following Additional Packages. Angular v6 is the first release of Angular that whole the Framework, Material, and CLI. @angular/core now depends on.

  1. TypeScript 2.72.
  2. RxJS 6.0.0
  3. tslib 1.9.0
  4. Node 8.9 or higher version

The CLI generated project has dependencies that need Node 8.9 or higher version. Let’s update NPM, you can run the following command in the terminal.

npm i npm@latest -g

Using the following command to install the latest versions:

npm install -g @angular/cli

Create an Angular 6 Project

After the node and NPM upgrade to the latest version, you can run the following command to generate an angular 6 projects.

ng new myapp

So, our angular 6 application generate with TypeScript and RxJS contains some breaking modification and hence a new package, rxjs-compat, can be installed alongside RxJS 6 for providing a compatibility layer while upgrading your code to the new syntax.

Angular 6 Project Structure

Now, our project will create. You can observe the folder structure in Solution Explorer as shown in the following image. Also, you can run the following commands to see angular 6 apps running at localhost:4200

cd myapp
ng serve

CRUD Operation In Angular 6 structure

So, our project files are generated with the help of CLI command which we need to understand here. We have angular.json file generated that has all the application configuration parameters. The configuration data related to the index.html, main.ts where all the modules are bundled.

You can also see the final application output directory configuration and configuration specific to environments such as development and production can found here.

We have a package.json file in that directory. It contains a lot of meta-data about all the project dependencies.
and We have also tsconfig.json file for typescript configuration. Inside the scr/app folder path we have defined our components and when the request for localhost:4200 made, AppComponent load in the browser.

Generating Angular component using CLI

Login component

Let’s generate the login component using the following command

ng g component login

generate login component angular  cli

login.component.html

<div class="row">
	<div class="col-md-6 col-md-offset-2">
	<h1>Login </h1>
	<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
	  <div class="form-group">
		<label for="email">Email address:</label>
		<input type="email" class="form-control" formControlName="email" id="email">
		<div *ngIf="submitted && loginForm.controls.email.errors" class="error">
		  <div *ngIf="loginForm.controls.email.errors.required">Email is required</div>
		</div>
	  </div>
	  <div class="form-group">
		<label for="pwd">Password:</label>
		<input type="password" class="form-control" formControlName="password" id="pwd">
		<div *ngIf="submitted && loginForm.controls.password.errors" class="error">
		  <div *ngIf="loginForm.controls.password.errors.required">Password is required</div>
		</div>
	  </div>
	  <button class="btn btn-default">Login</button>
	  <div *ngIf="invalidLogin" class="error">
		<div>Invalid credentials.</div>
	  </div>
	</form>
	</div>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Router} from "@angular/router";
import {first} from "rxjs/operators";
import {AuthenticationService} from "../service/auth.service";

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

loginForm: FormGroup;
submitted: boolean = false;
invalidLogin: boolean = false;
constructor(private formBuilder: FormBuilder, private router: Router, private authService: AuthenticationService) { }

onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
  return;
}
if(this.loginForm.controls.email.value == 'james@gmail.com' && this.loginForm.controls.password.value == 'password') {
	this.router.navigate(['list-employee']);
}else {
  this.invalidLogin = true;
}
}

ngOnInit() {
this.loginForm = this.formBuilder.group({
  email: ['', Validators.required],
  password: ['', Validators.required]
});
}

We have generated a login component. After the employee successfully login, it will redirect to the employee list page and then the employee can perform crud operation.

Add Employee component

ng g component add-employee

post data component using angular cli

add-employee.component.html

<div class="col-md-6">
<h2 class="text-center">Add employee</h2>
<form [formGroup]="addForm" (ngSubmit)="onSubmit()">
<div class="form-group">
  <label for="email">Email address:</label>
  <input type="email" formControlName="email" placeholder="Email" name="email" class="form-control" id="email">
</div>

<div class="form-group">
  <label for="firstName">First Name:</label>
  <input formControlName="firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
</div>

<div class="form-group">
  <label for="lastName">Last Name:</label>
  <input formControlName="lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
</div>

<button class="btn btn-success">Update</button>
</form>
</div>

add-employee.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {employeeservice} from "../service/employee.service";
import {first} from "rxjs/operators";
import {Router} from "@angular/router";

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

constructor(private formBuilder: FormBuilder,private router: Router, private employeeservice: employeeservice) { }

addForm: FormGroup;

ngOnInit() {

this.addForm = this.formBuilder.group({
  id: [],
  email: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required]
});

}
onSubmit() {
this.employeeservice.createemployee(this.addForm.value)
  .subscribe( data => {
	this.router.navigate(['list-employee']);
  });
}
}

Update Employee component

ng g component edit-employee

update component using angular 6

edit-employee.component.html

<div class="col-md-6">
<h2 class="text-center">Edit employee</h2>
<form [formGroup]="editForm" (ngSubmit)="onSubmit()">
<div class="form-group">
  <label for="email">Email address:</label>
  <input type="email" formControlName="email" placeholder="Email" name="email" class="form-control" id="email">
</div>

<div class="form-group">
  <label for="firstName">First Name:</label>
  <input formControlName="firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
</div>

<div class="form-group">
  <label for="lastName">Last Name:</label>
  <input formControlName="lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
</div>

<button class="btn btn-success">Update</button>
</form>
</div>

edit-employee.component.ts

import { Component, OnInit } from '@angular/core';
import {employeeservice} from "../service/employee.service";
import {Router} from "@angular/router";
import {employee} from "../model/employee.model";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {first} from "rxjs/operators";

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

employee: employee;
editForm: FormGroup;
constructor(private formBuilder: FormBuilder,private router: Router, private employeeservice: employeeservice) { }

ngOnInit() {
let employeeId = localStorage.getItem("editemployeeId");
if(!employeeId) {
  alert("Invalid action.")
  this.router.navigate(['list-employee']);
  return;
}
this.editForm = this.formBuilder.group({
  id: [],
  email: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required]
});
this.employeeservice.getemployeeById(+employeeId)
  .subscribe( data => {
	this.editForm.setValue(data);
  });
}

onSubmit() {
this.employeeservice.updateemployee(this.editForm.value)
  .pipe(first())
  .subscribe(
	data => {
	  this.router.navigate(['list-employee']);
	},
	error => {
	  alert(error);
	});
}
}

Display Employee List

ng g component list-employee

display record in angular 6

Following is list-employee.component.html.


<div class="col-md-6">
<h2> employee Details</h2>
<button class="btn btn-danger" (click)="addemployee()"> Add employee</button>
<table class="table table-striped">
<thead>
<tr>
  <th class="hidden">Id</th>
  <th>FirstName</th>
  <th>LastName</th>
  <th>Email</th>
  <th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
  <td class="hidden"></td>
  <td></td>
  <td></td>
  <td></td>
  <td><button class="btn btn-danger" (click)="deleteemployee(employee)"> Delete</button>
	<button class="btn btn-danger" (click)="editemployee(employee)" style="margin-left: 20px;"> Edit</button></td>
</tr>
</tbody>
</table>
</div>

list-employee.component.ts

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {employeeservice} from "../service/employee.service";
import {employee} from "../model/employee.model";

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

employees: employee[];

constructor(private router: Router, private employeeservice: employeeservice) { }

ngOnInit() {
this.employeeservice.getemployees()
  .subscribe( data => {
	this.employees = data;
  });
}

deleteemployee(employee: employee): void {
this.employeeservice.deleteemployee(employee.id)
  .subscribe( data => {
	this.employees = this.employees.filter(u => u !== employee);
  })
};

editemployee(employee: employee): void {
localStorage.removeItem("editemployeeId");
localStorage.setItem("editemployeeId", employee.id.toString());
this.router.navigate(['edit-employee']);
};

addemployee(): void {
this.router.navigate(['add-employee']);
};
}

Now that we created our routing configuration. and also configured to use LoginComponent as a default component. Also, we need to include it in the main module – app.module.ts

import { RouterModule, Routes } from '@angular/router';
import {LoginComponent} from "./login/login.component";
import {AddemployeeComponent} from "./add-employee/add-employee.component";
import {ListemployeeComponent} from "./list-employee/list-employee.component";
import {EditemployeeComponent} from "./edit-employee/edit-employee.component";

const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'add-employee', component: AddemployeeComponent },
{ path: 'list-employee', component: ListemployeeComponent },
{ path: 'edit-employee', component: EditemployeeComponent },
{path : '', component : LoginComponent}
];

export const routing = RouterModule.forRoot(routes);

Add AuthenticationService

In the app.module.ts file, we want to include the AuthenticationService in below code. because we have actually hard-coded the employee name and password in the login component.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import {routing} from "./app.routing";
import {AuthenticationService} from "./service/auth.service";
import {ReactiveFormsModule} from "@angular/forms";
import {HttpClientModule} from "@angular/common/http";
import { AddemployeeComponent } from './add-employee/add-employee.component';
import { EditemployeeComponent } from './edit-employee/edit-employee.component';
import {ListemployeeComponent} from "./list-employee/list-employee.component";
import {employeeservice} from "./service/employee.service";

@NgModule({
declarations: [
AppComponent,
LoginComponent,
ListemployeeComponent,
AddemployeeComponent,
EditemployeeComponent
],
imports: [
BrowserModule,
routing,
ReactiveFormsModule,
HttpClientModule
],
providers: [AuthenticationService, employeeservice],
bootstrap: [AppComponent]
})
export class AppModule { }

Create Service in Angular

Let’s generate employee service using the following CLI command.

ng g service employee

After that insert below code into the employee.service.ts file

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Employee  } from "../model/employee .model";

@Injectable()
export class EmployeeService {
  constructor(private http: HttpClient) { }
  baseUrl: string = 'http://localhost:8080/Employee-portal/employee';

  getEmployees() {
    return this.http.get<Employee[]>(this.baseUrl);
  }

  getEmployeeById(id: number) {
    return this.http.get<Employee>(this.baseUrl + '/' + id);
  }

  createEmployee(employee: Employee) {
    return this.http.post(this.baseUrl, user);
  }

  updateEmployee(employee: Employee) {
    return this.http.put(this.baseUrl + '/' + user.id, employee);
  }

  deleteEmployee (id: number) {
    return this.http.delete(this.baseUrl + '/' + id);
  }
}

API Implementation for Angular using .NET Core API

here, we have implemented following .NET core API code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotnetCoreApi.Models;
using DotnetCoreApi.Repository;
using Microsoft.AspNetCore.Mvc;

namespace DotnetCoreApi.Controllers
{
  [Route("api/employees")]
  [ApiController]
  public class employeesController : ControllerBase
    {
        IemployeeRepository employeeRepository;
        public employeeController(IemployeeRepository _employeeRepository)
        {
            employeeRepository = _employeeRepository;
        }

        [HttpGet]
        [Route("Getemployees")]
        public async Task Getemployees()
        {
            try
            {
                var employeelist = await employeeRepository.Getemployees();
                if (employeelist == null)
                {
                    return NotFound();
                }
                return Ok(employeelist);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [Httpemployee]
        [Route("Addemployee")]
        public async Task Addemployee([FromBody]employees model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var employeeId = await employeeRepository.Addemployee(model);
                    if (employeeId > 0)
                    {
                        return Ok(employeeId);
                    }
                    else
                    {
                        return NotFound();
                    }
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }
            return BadRequest();
        }

        [HttpDelete]
        [Route("Deleteemployee")]
        public async Task Deleteemployee(int? employeeId)
        {
            int result = 0;

            if (employeeId == null)
            {
                return BadRequest();
            }

            try
            {
                result = await employeeRepository.Deleteemployee(employeeId);
                if (result == 0)
                {
                    return NotFound();
                }
                return Ok();
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpPut]
        [Route("Updateemployee")]
        public async Task Updateemployee([FromBody]employee model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await employeeRepository.Updateemployee(model);

                    return Ok();
                }
                catch (Exception ex)
                {
                    if (ex.GetType().FullName == 
                             "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException")
                    {
                        return NotFound();
                    }
                    return BadRequest();
                }
            }
            return BadRequest();
        }
    }
}

Thanks for Reading Article! I hope this get’s you started the app using Angular 6 and .NET Core.

Leave a Reply

Your email address will not be published. Required fields are marked *