Thursday, 1 August 2019

Implementing Crud operation & Angular Route using Angular6 & Webapi2




View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication8.Models
{
    public class EMPVM
    {
        public int EID { get; set; }
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        public string PASSWORD { get; set; }
        public string GENDER { get; set; }
        public int? CID { get; set; }
        public int? SID { get; set; }
        public List<int> LHOBBY { get; set; }
    }
}

Web api :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication8.Models;

namespace WebApplication8.Controllers
{
    [RoutePrefix("api/Emp")]
    public class EmpController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public HttpResponseMessage Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex);
            }
        }
        [HttpGet]
        [Route("Hobbies")]
        public HttpResponseMessage Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Emps")]
        public HttpResponseMessage Emps()
        {
            try
            {

                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.EMPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Emp/{EID:int}",Name ="Get")]
        public HttpResponseMessage Emp(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMPVM vm = obj.EMPs.Select(n => new EMPVM { EID = n.EID, NAME = n.NAME, ADDRESS = n.ADDRESS, PASSWORD = n.PASSWORD, GENDER = n.GENDER, CID = n.CID, SID = n.SID }).SingleOrDefault(m => m.EID == EID);
                    vm.LHOBBY = obj.HMAPs.Where(p => p.EID == EID).Select(q => q.HID.Value).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK,vm);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("States/{CID:int}")]
        public HttpResponseMessage States(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = new EMP();
                    emp.EID = vm.EID;
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.CID;
                    emp.SID = vm.SID;
                    obj.Entry(emp).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.LHOBBY.Select(p => new HMAP { EID = vm.EID, HID = p }).ToList());
                    obj.SaveChanges();
                    var req= Request.CreateResponse(HttpStatusCode.Created,"Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Get",new { EID=vm.EID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPut]
        [Route("Update")]
        public HttpResponseMessage Update(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = obj.EMPs.Find(vm.EID);
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.CID;
                    emp.SID = vm.SID;
                    obj.Entry(emp).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.LHOBBY.Select(p => new HMAP { EID = vm.EID, HID = p }).ToList());
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                 
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public HttpResponseMessage Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.EMPs.Find(EID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(p=>p.EID==EID));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Delted.");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }

}

app.component.html :

<div style="padding:5px" class="container">
 
   <ul class="nav nav-tabs">

    <li routerLinkActive="Active">

      <a routerLink="list">Empioyee</a>

    </li>

    <li routerLinkActive="Active">

       <a routerLink="create">Department</a>

     </li>

   </ul>

 <br>

 <router-outlet></router-outlet>


 </div>

Angular Models :

export class COUNTRY {
    CID: number;
    CNAME: string;
}

export class STATE {
    SID: number;
    SNAME: string;
    CID: number;
}
export class HOBBY {
    HID: number;
    HNAME: string;
}
export class EMPVM {
    EID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    CID: number;
    SID: number;
    LHOBBY: number[];
}


Angular Service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { EMPVM, COUNTRY, STATE, HOBBY } from './chinai.model';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class ChinaiService {
    baseUrl='http://localhost:65426/api/Emp';
    constructor(private http: HttpClient){
    }
    Getc(): Promise<COUNTRY[]> {
        return this.http.get<COUNTRY[]>(`${this.baseUrl}/${"Countries"}`)
        .toPromise();
    }
    Geth(): Promise<HOBBY[]> {
        return this.http.get<HOBBY[]>(`${this.baseUrl}/${"Hobbies"}`)
        .toPromise();
    }
    Gets(cid: number): Promise<STATE[]> {
        return this.http.get<STATE[]>(`${this.baseUrl}/${"States"}/${cid}`)
        .toPromise();
    }
    Get(eid: number): Promise<EMPVM> {
        return this.http.get<EMPVM>(`${this.baseUrl}/${"Emp"}/${eid}`)
        .toPromise();
    }
    Gete(): Promise<EMPVM[]> {
        return this.http.get<EMPVM[]>(`${this.baseUrl}/${"Emps"}`)
        .toPromise();
    }
    Save(emp: EMPVM): Promise<string> {
        return this.http.post<string>(`${this.baseUrl}/${"Save"}`
        ,JSON.stringify(emp)
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }
    Update(emp: EMPVM): Promise<string> {
        return this.http.put<string>(`${this.baseUrl}/${"Update"}`
        ,JSON.stringify(emp)
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }
    Delete(eid: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${"Delete"}/${eid}`
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }

listchinai.component.html :

<div class="row">

    <div class="col-lg-4">
        <input type="button" class="btn btn-primary" value="Add New" (click)="add()" style="width:80px" />
    </div>
    <div class="col-lg-4">
    </div>
    <div class="col-lg-4">
    </div>
</div><br>
<div class="row">
    <div class="col-lg-12">
        <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
            <thead class="bg bg-primary">
                <tr>
                    <th>Sl No.</th>
                    <th>NAME</th>
                    <th>GENDER</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list;let i=index">
                    <td>{{i+1}}</td>
                    <td>{{c.NAME|CustomPipe1:c.GENDER}}</td>
                    <td>{{c.GENDER}}</td>
                    <td>
                        <a [routerLink]="['/create',c.EID]">Edit</a> |
                        <a (click)="del(c.EID)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

listchinai.component.ts :

import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { ChinaiService } from './chinai.service';
import { EMPVM } from './chinai.model';

@Component({
  selector: 'app-listchinai',
  templateUrl: './listchinai.component.html',
  styleUrls: ['./listchinai.component.css']
})
export class ListchinaiComponent implements OnInit {
list: EMPVM[];
  constructor(private ch: ChinaiService, private ru: Router) { }

  ngOnInit() {
   this.fill();
  }
  add(): void {
    this.ru.navigate(['/create']);
  }
  fill(): void {
    this.ch.Gete().then(data => this.list= data);
  }
  del(eid: number): void {
    if (confirm('Do you want to delete it.')) {
      this.ch.Delete(eid).then(data => {
        alert(data);
        this.fill();
      });
    }
  }
}

createchinai.component.html :

<form class="form-horizontal" #frmEmp="ngForm">
  <div class="form-group" [class.has-success]="EID.valid" [class.has-error]="EID.invalid && EID.touched">
      <label class="control-label col-lg-4">EID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required name="EID" [(ngModel)]="EMP.EID" #EID="ngModel" />
      </div>
      <span class="help-block" *ngIf="EID.invalid && EID.touched">Eid should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
      <label class="control-label col-lg-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required name="NAME" [(ngModel)]="EMP.NAME" #NAME="ngModel" />
      </div>
      <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="ADDRESS.valid" [class.has-error]="ADDRESS.invalid && ADDRESS.touched">
      <label class="control-label col-lg-4">ADDRESS</label>
      <div class="col-lg-4">
          <textarea class="form-control" required name="ADDRESS" [(ngModel)]="EMP.ADDRESS" #ADDRESS="ngModel"></textarea>
      </div>
      <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">Address should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="PASSWORD.valid" [class.has-error]="PASSWORD.invalid && PASSWORD.touched">
      <label class="control-label col-lg-4">PASSWORD</label>
      <div class="col-lg-4">
          <input type="password" class="form-control" required name="PASSWORD" [(ngModel)]="EMP.PASSWORD" #PASSWORD="ngModel" />
      </div>
      <span class="help-block" *ngIf="PASSWORD.invalid && PASSWORD.touched">Password should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="GENDER.valid" [class.has-error]="GENDER.invalid && GENDER.touched">
      <label class="control-label col-lg-4">GENDER</label>
      <div class="col-lg-4">
          <input type="radio" required name="GENDER" [(ngModel)]="EMP.GENDER" #GENDER="ngModel" value="Male" />Male
          <input type="radio" required name="GENDER" [(ngModel)]="EMP.GENDER" #GENDER="ngModel" value="Female" />Female
      </div>
      <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">Please select a gender.</span>
  </div>
  <div class="form-group" [class.has-success]="LHOBBY.valid" [class.has-error]="LHOBBY.invalid && LHOBBY.touched">
      <label class="control-label col-lg-4">HOBBY</label>
      <div class="col-lg-4">
          <select class="form-control" multiple="multiple" required name="LHOBBY" [(ngModel)]="EMP.LHOBBY" #LHOBBY="ngModel">
              <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="LHOBBY.invalid && LHOBBY.touched">Please select a hobby.</span>
  </div>
  <div class="form-group" [class.has-success]="CID.valid" [class.has-error]="CID.invalid && CID.touched">
      <label class="control-label col-lg-4">COUNTRY</label>
      <div class="col-lg-4">
          <select class="form-control" required name="CID" [(ngModel)]="EMP.CID" #CID="ngModel" (change)="fillddl()">
              <option [ngValue]=null >Select</option>
              <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
  </div>
  <div class="form-group" [class.has-success]="SID.valid" [class.has-error]="SID.invalid && SID.touched">
      <label class="control-label col-lg-4">STATE</label>
      <div class="col-lg-4">
          <select class="form-control" required name="SID" [(ngModel)]="EMP.SID" #SID="ngModel">
                <option [ngValue]=null >Select</option>
              <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
  </div>
  <div class="form-group">
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
          <input type="button" class="btn btn-primary" style="width:80px" value="Save" (click)="save(frmEmp.invalid)" />
          <input type="button" class="btn btn-primary" style="width:80px" value="Reset" (click)="reset(frmEmp)" /><br>
          <a [routerLink]="['/list']" >Back To List</a>
      </div>
  </div>
</form>

createchinai.component.ts :


import { Component, OnInit, ViewChild } from '@angular/core';
import { COUNTRY, STATE, EMPVM, HOBBY } from './chinai.model';
import { ChinaiService } from './chinai.service';
import {  ActivatedRoute, Router } from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-createchinai',
  templateUrl: './createchinai.component.html',
  styleUrls: ['./createchinai.component.css']
})
export class CreatechinaiComponent implements OnInit {
EMP: EMPVM;
listc: COUNTRY[];
lists: STATE[];
listh: HOBBY[];
Eid: number;
@ViewChild('frmEmp') public empfrm: NgForm;
  constructor(private cs: ChinaiService, private ru: Router , private ac: ActivatedRoute) { }

  ngOnInit() {
   
    this.CLR();
    this.cs.Getc().then(data => this.listc = data);
    this.cs.Geth().then(data => this.listh = data);
    this.Eid = this.ac.snapshot.params['id'];
    if (this.Eid !== null) {
      this.cs.Get(this.Eid).then(data => {
        this.fx(data.CID);
        this.EMP = data;
      });
    }
  }
  fillddl(): void {
   this.fx(this.EMP.CID);
  }
  fx(cid: number): void {
    this.cs.Gets(cid).then(data => this.lists = data);
  }
  save(isValid: boolean): void {
    if (!isValid){
      if (this.Eid === undefined) {
        this.cs.Save(this.EMP).then(data => {
          alert(data);
          this.ru.navigate(['\list']);
        });
      } else {
        this.cs.Update(this.EMP).then(data => {
          alert(data);
          this.ru.navigate(['\list']);
        });
      }
      
    }
    this.empfrm.reset();
  }
  reset(frme: NgForm): void {
   frme.reset();
  }
CLR(): void {
  this.EMP = {
     EID: null,
     NAME: null,
     ADDRESS: null,
     PASSWORD: null,
     GENDER: null,
     LHOBBY:[],
     CID: null,
     SID: null
  };
}
}

Augular Pipe :

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'CustomPipe1'
})
export class ChinaiPipe implements PipeTransform {
    transform(value: string, gender: string): string {
            if (gender.toLowerCase() === "male" ){
              return "Mr. " + value;   
            }else {
                return "Miss. " + value;
            }
    }
}

app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';


import { HttpClientModule } from '@angular/common/http';


import { RouterModule, Routes } from '@angular/router';
import { CreatechinaiComponent } from './chinai/createchinai.component';
import { ListchinaiComponent } from './chinai/listchinai.component';
import { ChinaiService } from './chinai/chinai.service';
import { ChinaiPipe } from './chinai/chinai.pipe';



const appRoutes: Routes = [
  { path: 'list', component: ListchinaiComponent },
  { path: 'create/:id', component: CreatechinaiComponent  },
  { path: 'delete/:id', component: CreatechinaiComponent  },
  { path: 'create', component: CreatechinaiComponent  },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: '**', component: ListchinaiComponent  }
];
@NgModule({
  declarations: [
    AppComponent,
    CreatechinaiComponent,
    ListchinaiComponent,
    ChinaiPipe
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    FormsModule
  ],
  providers: [ChinaiService],
  bootstrap: [AppComponent]
})
export class AppModule { }




No comments:

Post a Comment