Create Table in Database
Visual Studio 2017
File
New
Project
Select Web
Choose
ASP.NET Web Application(.NET Framework)
Project
Name : WebAPI after select location project folder
Ok
Click on Add button
Click on next Button
Click on Ok Button
Then click on Finish Button
Created Web API
Folder Name: Models --- > DBModels.edmx --- > DBModels.tt --- > Employee.cs
//------------------------------------------------------------------------------
//
<auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause
unexpected behavior in your application.
// Manual changes to this file will be
overwritten if the code is regenerated.
//
</auto-generated>
//------------------------------------------------------------------------------
namespace WebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class Employee
{
public int
EmployeeID { get; set; }
public string FullName
{ get; set; }
public string EMPCode
{ get; set; }
public string Mobile {
get; set; }
public string Position
{ get; set; }
}
}
Rebuild solution
Controllers Folder right click
EmployeesController.cs in Controllers
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebAPI.Models;
namespace WebAPI.Controllers
{
public class EmployeesController :
ApiController
{
private DBModel db = new DBModel();
// GET:
api/Employees
[HttpGet]
[Route("API/GetEmployees")]
public IQueryable<Employee> GetEmployees()
{
return db.Employees;
}
// PUT:
api/Employees/5
[HttpPut]
[Route("API/PutEmployee")]
[ResponseType(typeof(void))]
public IHttpActionResult PutEmployee(Employee employee)
{
if (employee.EmployeeID ==0)
{
return BadRequest();
}
db.Entry(employee).State =
EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(employee.EmployeeID))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST:
api/PostEmployee
[HttpPost]
[Route("API/PostEmployee")]
[ResponseType(typeof(Employee))]
public IHttpActionResult PostEmployee(Employee employee)
{
db.Employees.Add(employee);
db.SaveChanges();
// return
CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID },
employee);
return StatusCode(HttpStatusCode.OK, employee);
}
// DELETE:
api/Employees/5
[HttpGet]
[Route("API/DeleteEmployee")]
[ResponseType(typeof(Employee))]
public IHttpActionResult DeleteEmployee(int id)
{
Employee employee =
db.Employees.Find(id);
if (employee == null)
{
return NotFound();
}
db.Employees.Remove(employee);
db.SaveChanges();
return Ok(employee);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool
EmployeeExists(int id)
{
return db.Employees.Count(e => e.EmployeeID == id) > 0;
}
}
}
****************************** WebAPI Part is Completed ******************************
Next automatically install Microsoft.AspNet.WebApi.Cors
After install solution then
WebAPI Project build solution
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebAPI
{
public static class WebApiConfig
{
private static string headers;
private static string methods;
public static void Register(HttpConfiguration config)
{
//Enable CORs
config.EnableCors(new EnableCorsAttribute("*", headers = "*", methods = "*"));
// Web API
configuration and services
// Web API
routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Create Angular Project
create
Visual Studio Code
Open Created webAPI folder
select folder
ng new Angular7
cd Angular7
ng serve --open
Created all folders
angular.json
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"Angular7": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/Angular7",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css",
"node_modules/ngx-toastr/toastr.css" ],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "Angular7:build"
},
"configurations": {
"production": {
"browserTarget": "Angular7:build:production"
}
}},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "Angular7:build"
}},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "src/tsconfig.app.json", "src/tsconfig.spec.json" ], "exclude": [ "**/node_modules/**" ] }} }}, "Angular7-e2e": { "root": "e2e/", "projectType": "application", "prefix": "", "architect": { "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "Angular7:serve" }, "configurations": { "production": { "devServerTarget": "Angular7:serve:production" } }}, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": "e2e/tsconfig.e2e.json", "exclude": [ "**/node_modules/**" ]
] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "src/tsconfig.app.json", "src/tsconfig.spec.json" ], "exclude": [ "**/node_modules/**" ] }} }}, "Angular7-e2e": { "root": "e2e/", "projectType": "application", "prefix": "", "architect": { "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "Angular7:serve" }, "configurations": { "production": { "devServerTarget": "Angular7:serve:production" } }}, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": "e2e/tsconfig.e2e.json", "exclude": [ "**/node_modules/**" ]
}}
}}
},
"defaultProject": "Angular7"
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular7</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<!-- <script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script> -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// import { ToastrModule } from 'ngx-toastr';
import { AppComponent } from './app.component';
import { EmployeesComponent } from './employees/employees.component';
import { EmployeeComponent } from './employees/employee/employee.component';
import { EmployeeListComponent } from
'./employees/employee-list/employee-list.component';
import { EmployeeService } from './shared/employee.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
EmployeesComponent,
EmployeeComponent,
EmployeeListComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
// ToastrModule
],
providers: [EmployeeService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
<div class="col-md-12">
<app-employees></app-employees>
</div>
employees ---> employees.component.html
<div class="jumbston">
<h3 class="display-6 text-center">
Employee Register
</h3>
<hr>
<div class="row">
<div class="col-md-4">
<app-employee></app-employee>
</div>
<div class="col-md-8">
<app-employee-list></app-employee-list>
</div>
</div>
</div>
employees ---> employees.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
employees ---> employee ---> employee.component.html
<form #form="ngForm" (submit)="onSubmit(form)" autocomplete="off">
<input type="hidden" name="EmployeeID" #EmployeeID="ngModel"
[(ngModel)]="service.formData.EmployeeID">
<div class="form-group">
<label for="">Full Name</label>
<input name="FullName" #FullName="ngModel" [(ngModel)]="service.formData.FullName"
class="form-control" placeholder="Full Name" required>
<div class="validation-error" *ngIf="FullName.invalid && FullName.touched">
This field is required</div> </div> <div class="form-group"> <label for="">Position</label> <input name="Position" #Position="ngModel" [(ngModel)]="service.formData.Position" class="form-control" placeholder="Position" required> </div>
This field is required</div> </div> <div class="form-group"> <label for="">Position</label> <input name="Position" #Position="ngModel" [(ngModel)]="service.formData.Position" class="form-control" placeholder="Position" required> </div>
<div class="row">
<div class="form-group col-md-6">
<label for="">EMP Code</label>
<input name="EMPCode" #EMPCode="ngModel" [(ngModel)]="service.formData.EMPCode"
class="form-control" placeholder="EMP Code" required>
</div>
<div class="form-group col-md-6">
<label for="">Mobile</label>
<input name="Mobile" #FullName="ngModel" [(ngModel)]="service.formData.Mobile"
class="form-control" placeholder="Mobile" required>
</div>
</div>
<div>
<button type="submit" [disabled]="form.invalid"
class="btn btn-lg btn-info btn-block">Submit</button>
</div>
</form>
employees ---> employee ---> employee.component.ts
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from 'src/app/shared/employee.service';
import { NgForm } from '../../../../node_modules/@angular/forms';
// import { ToastrService} from 'ngx-toastr';
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
constructor(private service: EmployeeService,
// private toastr : ToastrService
) { }
ngOnInit() {
this.restForm();
}
restForm(form?: NgForm) {
if (form != null)
form.resetForm();
this.service.formData = {
EmployeeID: null,
FullName: '',
Position: '',
EMPCode: '',
Mobile: '',
}
}
onSubmit(form:NgForm){
debugger;
if(form.value.EmployeeID == null)
this.insertRecord(form)
else
this.updateRecord(form);
}
insertRecord(form:NgForm){
this.service.postEmployee(form.value).subscribe(res =>{
// this.toastr.success('Insert Successfully', 'EMP. Register');
this.restForm(form);
this.service.refreshList();
});
}
updateRecord(form:NgForm){
this.service.putEmployee(form.value).subscribe(res =>{
// this.toastr.warning('Updated Successfully', 'EMP. Register');
this.restForm(form);
this.service.refreshList();
});
}
deleteRecord(form:NgForm){
this.service.deleteEmployee(form.value).subscribe(res =>{
// this.toastr.warning('Updated Successfully', 'EMP. Register');
this.restForm(form);
this.service.refreshList();
});
}
}
employees ---> employee ---> employee-list.component.html
<table class="table table-bordered table-hover">
<tr *ngFor="let emp of service.list">
<td (click)="populateForm(emp)">[{{emp.EMPCode}}] - {{emp.FullName}} </td>
<td (click)="populateForm(emp)">{{emp.FullName}}</td>
<td (click)="populateForm(emp)">{{emp.Position}}</td>
<td (click)="populateForm(emp)">{{emp.Mobile}}</td>
<td><button (click)="onDelete(emp.EmployeeID)"
class="btn btn-danger btn-sm">X</button></td>
</tr>
</table>
employees ---> employee ---> employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../../shared/employee.service';
import { Employee } from '../../shared/employee.model';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
constructor(private service : EmployeeService,
//private toatr:ToastrService
) { }
ngOnInit() {
this.service.refreshList();
}
populateForm(emp:Employee){
this.service.formData=Object.assign({}, emp);
}
onDelete(id:number){
this.service.deleteEmployee(id).subscribe(res=>{
this.service.refreshList();
// this.toastr.warning('Delete Successfully', 'EMP. Register');
})
}
}
shared---> employee.models.ts
export class Employee {
EmployeeID:number;
FullName:string;
EMPCode:string;
Mobile:string;
Position:string;
}
shared---> employee.service.ts
import { Injectable } from '@angular/core';
import { Employee } from './employee.model';
import { HttpClient } from '@angular/common/http';
// import { ToastrService} from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
formData: Employee;
list: Employee[];
readonly rootURL = "http://localhost:51757/api";
constructor(private http: HttpClient) { }
// constructor(private http: HttpClient,
// private toastr : ToastrService) { }
postEmployee(formData: Employee) {
return this.http.post(this.rootURL + '/PostEmployee', formData);
//this.refreshList();
}
refreshList() {
//debugger;
this.http.get(this.rootURL + '/GetEmployees')
.toPromise().then(res => this.list = res as Employee[])
}
putEmployee(formData: Employee) {
//debugger;
return this.http.put(this.rootURL + '/PutEmployee', formData);
// this.refreshList();
}
deleteEmployee(id: number) {
if (confirm('Are you want to delete this record?'))
return this.http.get(this.rootURL + '/DeleteEmployee?id='+id);
// this.refreshList();
// this.toastr.info('Delete Successsfully', 'EMP. Register');
}
}
shared---> employee.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { EmployeeService } from './employee.service';
describe('EmployeeService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: EmployeeService = TestBed.get(EmployeeService);
expect(service).toBeTruthy();
});
});
OUTPUT
No comments:
Post a Comment