Sunday, 3 June 2018

CRUD operation using ANGULARJS 5 & webapi2


webapi code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    [RoutePrefix("api/Faculties")]
    public class FacultiesController : ApiController
    {
        [HttpGet]
        [Route("Allfaculties")]
        public IHttpActionResult Allfaculties()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.FACULTies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Facultie/{FID:int}",Name ="Facultie")]
        public IHttpActionResult Facultie(int FID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.FACULTies.Find(FID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(FACULTY fac)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.FACULTies.Add(fac);
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Facultie", new { FID = fac.FID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{FID:int}")]
        public IHttpActionResult Update([FromUri]int FID,[FromBody]FACULTY fac)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    FACULTY fACULTY = obj.FACULTies.Find(FID);
                    fACULTY.NAME = fac.NAME;
                    fACULTY.ADDRESS = fac.ADDRESS;
                    fACULTY.PASSWORD = fac.PASSWORD;
                    fACULTY.GENDER = fac.GENDER;
                    fACULTY.ISMARRIED = fac.ISMARRIED;
                    fACULTY.DID = fac.DID;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{FID:int}")]
        public IHttpActionResult Delete([FromUri]int FID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    FACULTY fACULTY = obj.FACULTies.Find(FID);
                    obj.FACULTies.Remove(fACULTY);
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }


    }
}


Create Angular 5 Application
I use Visual Studio Code Editor for Angular Project Development. In-order to create an angular 5 application you can use following Angular CLI command.


1
ng new AngularCRUD
It will create the application with name AngularCRUD  and install default packages from npm. In-order to run an angular application, you can use following command.


1
ng serve --open
it will open our application from default port number 4200, that means –  http://localhost:4200.

Add Required Angular 5 CRUD Components, Model and Service Class
Now we need to add 3 components. To add an angular component you can do this

ng g c faculty/createFaculty --spec false --flat true

Open appmodule.ts file, Make sure that newly added components are added to declarations array.

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

import { NgModule } from '@angular/core';

import { FormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { FacultyServices } from '../app/faculty/faculty.services';

import { AppComponent } from './app.component';

import { CreateFacultyComponent } from './faculty/create-faculty.component';

import { ToastrModule } from 'ngx-toastr';





@NgModule({

  declarations: [

    AppComponent,

       CreateFacultyComponent

  ],

  imports: [

    BrowserModule,

    FormsModule,

    HttpModule,

    ToastrModule.forRoot()

  ],

  providers: [FacultyServices],

  bootstrap: [AppComponent]

})

export class AppModule { }





Let’s Start the Design
We’ll use Bootstrap and Font-Awesome Icons For Application Design. So first of all add CDN reference for these style sheets inside index.html .

<form class="form-horizontal">

  <div class="form-group">

      <label class="col-lg-4 control-label">FID</label>

      <div class="col-lg-4">

          <input type="text" class="form-control" name="FID" [(ngModel)]="FACULTY.FID" />

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">NAME</label>

      <div class="col-lg-4">

          <input type="text" class="form-control" name="NAME" [(ngModel)]="FACULTY.NAME" />

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">ADDRESS</label>

      <div class="col-lg-4">

          <textarea class="form-control" name="ADDRESS" [(ngModel)]="FACULTY.ADDRESS" ></textarea>

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">PASSWORD</label>

      <div class="col-lg-4">

          <input type="password" class="form-control" name="PASSWORD" [(ngModel)]="FACULTY.PASSWORD" />

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">GENDER</label>

      <div class="col-lg-4">

          <input type="radio" value="Male" name="GENDER" [(ngModel)]="FACULTY.GENDER" />Male

          <input type="radio" value="Female" name="GENDER" [(ngModel)]="FACULTY.GENDER" />Female

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">ARE YOU MARRIED ?</label>

      <div class="col-lg-4">

          <input type="checkbox"  name="ISMARRIED" [(ngModel)]="FACULTY.ISMARRIED" />

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label">DEPATMENT</label>

      <div class="col-lg-4">

          <select class="form-control" name="DID" [(ngModel)]="FACULTY.DID">

              <option value="null">Select</option>

              <option *ngFor="let c of listd" value={{c.DID}}>{{c.DNAME}}</option>

          </select>

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label"></label>

      <div class="col-lg-4">

          <input type="button" value="Save" class="btn btn-primary" style="width:80px" (click)="save()" />

          <input type="button" value="Update" class="btn btn-primary" style="width:80px" (click)="update()" />

          <input type="button" value="Reset" class="btn btn-primary" style="width:80px" (click)="reset()" />

      </div>

  </div>

  <div class="form-group">

      <label class="col-lg-4 control-label"></label>

      <div class="col-lg-4">

          <table class="table table-bordered table-condensed table-hover table-responsive table-striped">

              <thead class="bg bg-primary">

                  <tr>

                      <th>FID</th>

                      <th>NAME</th>

                      <th>ACTION</th>

                  </tr>

              </thead>

              <tbody>

                  <tr *ngFor="let c of listf">

                      <td>{{c.FID}}</td>

                      <td>{{c.NAME}}</td>

                      <td>

                          <a (click)="edit(c.FID)">Edit</a> |

                          <a (click)="del(c.FID)">Delete</a>

                      </td>

                  </tr>

              </tbody>

              

          </table>

      </div>

  </div>

</form>



Update app.component.html as follows



<div class="container" style="margin-top:30px">

<app-create-faculty></app-create-faculty>

</div>



Create  Model Classes

export interface Ifaculty {
    FID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    ISMARRIED: Boolean;
    DID: number;
}

export interface Idept {
    DID: number;
    DNAME: string;
}

Create Service Classe

import { Injectable } from '@angular/core';
import { Http, Response, RequestMethod, RequestOptions, Headers } from '@angular/http';
import { Ifaculty, Idept } from '../faculty/faculty.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class FacultyServices {
    constructor(private _http: Http) { }
    Getd(): Observable<Idept[]> {
        return this._http.get('http://localhost:2292/api/Deptservices/Depts')
            .map((response: Response) => <Idept[]>response.json());
    }
    Getf(): Observable<Ifaculty[]> {
        return this._http.get('http://localhost:2292/api/Faculties/Allfaculties')
            .map((response: Response) => <Ifaculty[]>response.json());
    }
    Get(fid: number): Observable<Ifaculty> {
        return this._http.get('http://localhost:2292/api/Faculties/Facultie/' + fid)
            .map((response: Response) => <Ifaculty>response.json());
    }
    Save(fac: Ifaculty): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:2292/api/Faculties/Save', JSON.stringify(fac), requestOptions)
            .map((response: Response) => response.json());

    }
    Update(fac: Ifaculty): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:2292/api/Faculties/Update/' + fac.FID, JSON.stringify(fac), requestOptions)
            .map((response: Response) => response.json());

    }
    Delete(fid: number): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:2292/api/Faculties/Delete/' + fid, requestOptions)
            .map((response: Response) => response.json());
    }

}

ngx-toastr package installation
In-order to install the package, you can use following npm command.


1
npm install ngx-toastr --save
then add ToastrModule inside appmodule.ts file.


1
2
3
4
5
6
7
8
9
...
import { ToastrModule } from 'ngx-toastr';
@NgModule({
   ...
   imports: [
   ...
   ToastrModule.forRoot()
   ],
...
Then add toastr.css style-sheet reference in .angular-cli.json file.


1
2
3
4
5
6
...
"styles": [
        "styles.css",
        "../node_modules/ngx-toastr/toastr.css"
      ],
...
Now you can add following code inside faculty component typescript file.

import { Component, OnInit } from '@angular/core';
import { Ifaculty, Idept } from '../faculty/faculty.model';
import { FacultyServices } from '../faculty/faculty.services';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-create-faculty',
  templateUrl: './create-faculty.component.html',
  styleUrls: ['./create-faculty.component.css']
})
export class CreateFacultyComponent implements OnInit {
  FACULTY: Ifaculty;
  listd: Idept[];
  listf: Ifaculty[];
  constructor(private fs: FacultyServices, private ts: ToastrService) {
    this.reset();
    this.fill();
    this.fs.Getd().subscribe(data => this.listd = data);
  }

  ngOnInit() {
  }
  reset() {
    this.FACULTY = {
      FID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      GENDER: null,
      ISMARRIED: true,
      DID: null
    };
  }
  fill(): void {
    this.fs.Getf().subscribe(data => this.listf = data);
  }
  save(): void {
    this.fs.Save(this.FACULTY).subscribe();
    this.ts.success('Data Saved.', 'Alert Message');
    this.fill();
    this.reset();
  }
  edit(fid: number): void {
    this.fs.Get(fid).subscribe(data => this.FACULTY = data);
  }
  update(): void {
    this.fs.Update(this.FACULTY).subscribe();
    this.ts.success('Data Updated.', 'Alert Message');
    this.fill();
    this.reset();
  }
  del(fid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.fs.Delete(fid).subscribe();
      this.ts.success('Data Deleted.', 'Alert Message');
      this.fill();
    }
  }
}

No comments:

Post a Comment