Thursday 20 September 2018

Angular 4 Insert,Update, Delete with ASP.NET WEB API

Introduction
Angular 4  is more popular now days and for beginners, I will tell you what’s new IN Angular 4 and show you a practical example of angular 4 With ASP.NET Web API for inserting, deleting and displaying data using Angular 4
Basically, this article will demonstrate with example the following:
·       Step by step procedure to create ASP.NET Web API project  
·       Prerequisites and Setup for Angular 4
·       How to create Angular 4 Application and install Angular 4 packages  
·       How to create   service and component in Angular 4
·       How to get data from server side (Web api)
·       How to bind/Load/Fill data from Server side to HTML page using Angular 4
·       How to perform insert, edit, update and delete operation on view using Angular 4 data binding



Sujeet Bhujbal Angular


What is Angular
Angular is an Open Source which is developed by Google
Angular 4 is the latest version of Angular. It is a front-end web application platform

What’s new in Angular 4

 

1.     Reduced Size and Improved Performance
2.     Separate Animation Package
3.     ngIf with else : -We can use an else syntax in your templates
4.     As: - Introduced as new keyword, As Keywprd allows to store a result in a variable of the template, to use it in the element.
5.     Titlecase : - Angular 4 introduced a new titlecase pipe. This pipe is converts first letter of each word into uppercase
6.     Http  Adding search parameters to an HTTP request has been simplified
7.     Validators :- Added new validators like  required, minLength, maxLength and pattern.  Email validator helps you validate that the input is a valid email 

Sujeet Bhujbal Angular

What You Need

·       Basic knowledge of Angular
·       Angular CLI
Prerequisite
  • Node
  • Npm
  • Angular CLI
  • Typescript
  • Text editor- visual code
Install the below setup step by step, Using Visual Studio Code or Command prompt:
  • Node
  • Npm
  • Angular CLI
  • Typescript
  •  Visual code

Set up for angular 4
Verify version of Node
  • node -v
  • npm –v

Installing Angular CLI

npm install -g @angular/cli

Typescript Installation

First check typescript version using below command

 tsc –version

If Typescript is not installed then use command

npm install –g typescript

 

 

  

Step 1:  Start With Asp.net Web API

 

1.     Create Database WebAPIDB With below structure
CREATE TABLE [dbo].[Employee] (
    [EmployeeID] INT          IDENTITY (1, 1) NOT NULL,
    [FirstName]  VARCHAR (50) NULL,
    [LastName]   VARCHAR (50) NULL,
    [EmpCode]    VARCHAR (50) NULL,
    [Position]   VARCHAR (50) NULL,
    [Office]     VARCHAR (50) NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
);

2.      Generate Entity Model from Database Name as DBModel.edmx

3.     Add Web Api Controller
public class EmployeeController : ApiController
   {
       private MyDBEntities db = new MyDBEntities();
 
 
       public IQueryable<Employee> GetEmployees()
       {
           return db.Employees;
       }
 
 
 
       public IHttpActionResult PutEmployee(int id, Employee employee)
       {
 
           if (id != employee.EmployeeID)
           {
               return BadRequest();
           }
 
           db.Entry(employee).State = EntityState.Modified;
 
           try
           {
               db.SaveChanges();
           }
           catch (DbUpdateConcurrencyException)
           {
               if (!EmployeeExists(id))
               {
                   return NotFound();
               }
               else
               {
                   throw;
               }
           }
 
           return StatusCode(HttpStatusCode.NoContent);
       }
 
 
       [ResponseType(typeof(Employee))]
       public IHttpActionResult PostEmployee(Employee employee)
       {
 
           db.Employees.Add(employee);
           db.SaveChanges();
 
           return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
       }
 
 
       [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;
       }
   }
 


In the above class we have following methods
1.     GetEmployee() Method will return all the emloyees in JSON format
2.     PostEmployee() method will add new employee to database
3.     DeleteEmployee() method will delete existing employee

4.  Install Swagger Package Swashbuckle



Test Web Api Using  Swagger


 

 

  

Step 2:  Start With Angular 4

Step 1
1      Create a folder of the name EmployeeApplication  . Open Visual Studio Code.and open this folder in it. This folder will be used as the workspace for creating all the required files for the application.


 



4      Create new Angular projects is easy by using Angular CLI in the following way:

Go To Viewà Integrated Terminal

Cd EmployeeApplication 


$ ng new EmployeeApplication 


5      Run the following command from the command prompt.

          npm install



6      Serve the app locally

To serve the app locally, inside your newly created project, run the following command:

            ng serve


Open Chrome and add address http://localhost:4200/



Create New Employee Service using below command

ng generate service Employee


EmployeeService.js file is used for calling server side code by using $http. In EmployeeService.js file we have created an Angular  service called as EmployeeService. To call Web API EmployeeControllers for insert update,delete function we have created three functions in EmployeeService.js
We have created following method in service to Call Server Side Code

1.      postEmployee() : This will post data to server
2.     getEmployeeList() : This will fetch data from server
3.     deleteEmployee(): This will delete employee from server

export class EmployeeService {

  selectedEmployee : Employee;
  employeeList : Employee[];
  constructor(private http : Http) { }

  postEmployee(emp : Employee){
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({'Content-Type':'application/json'});
    var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
    return this.http.post('http://localhost:28750/api/Employee',body,requestOptions).map(x => x.json());
  }

  putEmployee(id, emp) {
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({ 'Content-Type': 'application/json' });
    var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
    return this.http.put('http://localhost:28750/api/Employee/' + id,
      body,
      requestOptions).map(res => res.json());
  }
  getEmployeeList(){
    this.http.get('http://localhost:28750/api/Employee')
    .map((data : Response) =>{
      return data.json() as Employee[];
    }).toPromise().then(x => {
      this.employeeList = x;
    })
  }

  deleteEmployee(id: number) {
    return this.http.delete('http://localhost:28750/api/Employee/' + id).map(res => res.json());
  }
}


Component in Angular :
Major part of the development with Angular 4 is done in the components

In Angular application, Components are basically classes that interact with the .html file of the component 
It consist of
1. Template
2. Class
3. Metadata


  We will get all details of component using below link


Create New Employee Component using below command

ng generate component Employee


export class EmployeeComponent implements OnInit {

  constructor(private employeeService: EmployeeService, private toastr: ToastrService) { }

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form != null)
      form.reset();
    this.employeeService.selectedEmployee = {
      EmployeeID: null,
      FirstName: '',
      LastName: '',
      EmpCode: '',
      Position: '',
      Office: ''
    }
  }

  onSubmit(form: NgForm) {
    if (form.value.EmployeeID == null) {
      this.employeeService.postEmployee(form.value)
        .subscribe(data => {
          this.resetForm(form);
          this.employeeService.getEmployeeList();
          this.toastr.success('New Record Added Succcessfully', 'Employee Register');
        })
    }
    else {
      this.employeeService.putEmployee(form.value.EmployeeID, form.value)
      .subscribe(data => {
        this.resetForm(form);
        this.employeeService.getEmployeeList();
        this.toastr.info('Record Updated Successfully!', 'Employee Register');
      });
    }
  }
}

Add another component for List

ng generate component EmployeeList


We are using ToasterService for showing notification on UI.
This component is used for showing employing list.It will fetch data from Web Api and will show on UI.
export class EmployeeListComponent implements OnInit {

  constructor(private employeeService: EmployeeService,private toastr : ToastrService) { }

  ngOnInit() {
    this.employeeService.getEmployeeList();
  }

  showForEdit(emp: Employee) {
    this.employeeService.selectedEmployee = Object.assign({}, emp);;
  }

  onDelete(id: number) {
    if (confirm('Are you sure to delete this record ?') == true) {
      this.employeeService.deleteEmployee(id)
      .subscribe(x => {
        this.employeeService.getEmployeeList();
        this.toastr.warning("Deleted Successfully","Employee Register");
      })
    }
  }
}




We are using below attributes
1.     The ng-model attribute is used for, Binding controls such as input, text area and selects in the view into the model
2.     ng-submit  : - The ng-submit directive submit a form to specified function
3.     ngModel : the ng-model attribute is used to bind the data in your model to the view presented to the user.

Add below UI To employee.component.html file

<form class="emp-form" #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
  <input type="hidden" name="EmployeeID" #EmployeeID="ngModel" [(ngModel)]="employeeService.selectedEmployee.EmployeeID">
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="FirstName" #FirstName="ngModel" [(ngModel)]="employeeService.selectedEmployee.FirstName"
        placeholder="First Name" required>
      <div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">This Field is Required.</div>
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="LastName" #LastName="ngModel" [(ngModel)]="employeeService.selectedEmployee.LastName" placeholder="Last Name"
        required>
      <div class="validation-error" *ngIf="LastName.invalid && LastName.touched">This Field is Required.</div>
    </div>
  </div>
  <div class="form-group">
    <input class="form-control" name="Position" #Position="ngModel" [(ngModel)]="employeeService.selectedEmployee.Position" placeholder="Position">
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" name="EmpCode" #EmpCode="ngModel" [(ngModel)]="employeeService.selectedEmployee.EmpCode" placeholder="Emp Code">
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employeeService.selectedEmployee.Office" placeholder="Office">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-8">
      <button [disabled]="!employeeForm.valid" type="submit" class="btn btn-lg btn-block btn-info">
        <i class="fa fa-floppy-o"></i> Submit</button>
    </div>
    <div class="form-group col-md-4">
      <button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeeForm)">
        <i class="fa fa-repeat"></i> Reset</button>
    </div>
  </div>
</form>


Add command Ng Serve to test your application

NPM Start
Open Chrome and add address http://localhost:4200/

By using this, you have successfully inserted data in the database and you have also shown this in the 

gridview. Click on submit





Please take a look at the attached code for more information. Download AngulaJsExample.zip
Happy programming!!
Don’t forget to leave your feedback and comments below!


Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
------------------------------------------------------------------------------