Saturday 16 June 2018

validation in angularjs 5 & web api 2

View Model :

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

namespace WebApplication2.Models
{
    public class STAPVM
    {
        public int STID { get; set; }
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        public string PASSWORD { get; set; }
        public string GENDER { get; set; }
        public bool? ISMARRIED { get; set; }
        public int? CID { get; set; }
        public int? SID { get; set; }
        public List<HOBBY> HLIST { get; set; }

        public STAPVM()
        {
            HLIST = new List<HOBBY>();
        }

    }
}

Web Api :

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Stapservices")]
    public class StapservicesController : ApiController
    {
        [Route("Countries")]
        [HttpGet]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Hobbies")]
        [HttpGet]
        public IHttpActionResult Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Staps")]
        [HttpGet]
        public IHttpActionResult Staps()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STAPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [Route("STATE/{CID:int}")]
        [HttpGet]
        public IHttpActionResult STATE(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [Route("Stap/{STID:int}",Name ="Stap")]
        [HttpGet]
        public IHttpActionResult Stap(int STID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAPVM vm = obj.STAPs.Select(e => new STAPVM { STID = e.STID, NAME = e.NAME, ADDRESS = e.ADDRESS, PASSWORD = e.PASSWORD, GENDER = e.GENDER, ISMARRIED = e.ISMARRIED, CID = e.CID, SID = e.SID }).SingleOrDefault(m => m.STID == STID);
                    var data = (
                        from x in obj.HMAPs.Where(e => e.STID == STID).ToList()
                        join y in obj.HOBBies on x.HID equals y.HID
                        select new HOBBY { HID = y.HID, HNAME = y.HNAME, STATUS = true }
                              ).ToList();
                    var data1 = obj.HOBBies.Select(e => new { e.HID, e.HNAME }).ToList().Except(data.Select(m => new { m.HID, m.HNAME })).ToList().Select(p => new HOBBY { HID = p.HID, HNAME = p.HNAME, STATUS = false }).ToList();
                    vm.HLIST = data.Union(data1).ToList();
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = new STAP();
                    st.STID = vm.STID;
                    st.NAME = vm.NAME;
                    st.ADDRESS = vm.ADDRESS;
                    st.PASSWORD = vm.PASSWORD;
                    st.GENDER = vm.GENDER;
                    st.ISMARRIED = vm.ISMARRIED;
                    st.CID = vm.CID;
                    st.SID = vm.SID;
                    obj.STAPs.Add(st);
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Where(m=>m.STATUS==true).Select(p => new HMAP { STID = vm.STID, HID = p.HID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Stap", new { STID = vm.STID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Update/{STID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int STID,[FromBody]STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = obj.STAPs.Find(STID);
                    st.NAME = vm.NAME;
                    st.ADDRESS = vm.ADDRESS;
                    st.PASSWORD = vm.PASSWORD;
                    st.GENDER = vm.GENDER;
                    st.ISMARRIED = vm.ISMARRIED;
                    st.CID = vm.CID;
                    st.SID = vm.SID;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == STID));
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Where(m=>m.STATUS==true).Select(p => new HMAP { STID = vm.STID, HID = p.HID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [Route("Delete/{STID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int STID, [FromBody]STAPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    STAP st = obj.STAPs.Find(STID);
                    obj.STAPs.Remove(st);
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == STID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}


Angular Model


export interface Istap {
    STID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    ISMARRIED: boolean;
    CID: number;
    SID: number;
    HLIST: Ihobby[];
}

export interface Icountry {
    CID: number;
    CNAME: string;
}

export interface Istate {
    SID: number;
    SNAME: string;
    CID: number;
}

export interface Ihobby {
    HID: number;
    HNAME: string;
    STATUS: boolean;
}

Angular Service :

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestMethod, RequestOptions } from '@angular/http';
import { Istap, Icountry, Istate, Ihobby } from '../create-stap/stap.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()

export class StapServices {

    constructor(private _hppt: Http) { }
    Getc(): Observable<Icountry[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Countries')
            .map((response: Response) => <Icountry[]>response.json());
    }
    Geth(): Observable<Ihobby[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Hobbies')
            .map((response: Response) => <Ihobby[]>response.json());
    }
    Gets(cid: number): Observable<Istate[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/STATE/' + cid)
            .map((response: Response) => <Istate[]>response.json());
    }
    Gete(): Observable<Istap[]> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Staps')
            .map((response: Response) => <Istap[]>response.json());
    }
    Get(stid: number): Observable<Istap> {
        return this._hppt.get('http://localhost:3592/api/Stapservices/Stap/' + stid)
            .map((response: Response) => <Istap>response.json());
    }
    Save(STAP: Istap): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._hppt.post('http://localhost:3592/api/Stapservices/Save', JSON.stringify(STAP), requestOptions)
            .map((res: Response) => <any>res.json());
    }
    Update(STAP: Istap): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._hppt.put('http://localhost:3592/api/Stapservices/Update/' + STAP.STID, JSON.stringify(STAP), requestOptions)
            .map((res: Response) => <any>res.json());
    }
    Delete(stid: number): any {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._hppt.delete('http://localhost:3592/api/Stapservices/Delete/' + stid, requestOptions)
            .map((res: Response) => <any>res.json());
    }
}

Angular  component :

import { Component, OnInit } from '@angular/core';
import { Istap, Icountry, Istate, Ihobby } from '../create-stap/stap.model';
import { StapServices } from '../create-stap/stap.services';

@Component({
  selector: 'app-create-stap',
  templateUrl: './create-stap.component.html',
  styleUrls: ['./create-stap.component.css']
})
export class CreateStapComponent implements OnInit {
  STAP: Istap;
  listc: Icountry[];
  lists: Istate[];
  listh: Ihobby[];
  list: Istap[];
  message: string;
  mark: number;
  errMessage: string;
  constructor(private stapservice: StapServices) {
    this.reset();
    this.stapservice.Getc().subscribe(data => this.listc = data);
    this.fill();
  }

  ngOnInit() {
  }
  fill(): void {
    this.stapservice.Gete().subscribe(res => this.list = res);
  }
  reset(): void {
    this.STAP = {
      STID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      GENDER: null,
      ISMARRIED: true,
      CID: null,
      SID: null,
      HLIST: []
    };
    this.stapservice.Geth().subscribe(data => this.STAP.HLIST = data);
  }
  fx(CID: number): void {
    this.stapservice.Gets(CID).subscribe(data => this.lists = data);
  }
  fillddl(): void {
    this.fx(this.STAP.CID);
  }
  save(isValid: boolean): void {
    if (!isValid) {
      this.stapservice.Save(this.STAP).subscribe(res => this.message = res.data);
      alert(this.message);
      this.reset();
      this.fill();
    }

  }
  edit(id: number): void {
    this.stapservice.Get(id).subscribe(res => this.STAP = res);
    this.fx(this.STAP.CID);
  }
  del(id: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.stapservice.Delete(id).subscribe(res => this.message = res.data);
      alert(this.message);
      this.fill();
    }
  }

  update(isValid: boolean): void {
    if (!isValid) {
      this.stapservice.Update(this.STAP).subscribe(res => this.message = res.data);
      alert(this.message);
      this.reset();
      this.fill();
    }

  }
  cvalidation(): void {
    this.mark = 0;
    this.STAP.HLIST.forEach(element => {
      if (element.STATUS === true) {
        this.mark = 1;
      }
    });
    if (this.mark === 0) { this.errMessage = 'Please select a hobby.'; } else { this.errMessage = ''; }
  }
}


Angular View :


<form class="form-horizontal" #stapForm="ngForm"  >
  <div class="form-group " [class.has-error]="STID.invalid && STID.touched" [class.has-success]="STID.valid">
      <label class="control-label col-lg-4">STID</label>
      <div class="col-lg-4">
          <input type="text"  name="STID" class="form-control" [(ngModel)]="STAP.STID" #STID="ngModel" required />
      </div>
      <span class="help-block" *ngIf="STID.invalid && STID.touched">
          STID 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" name="NAME" [(ngModel)]="STAP.NAME" #NAME="ngModel" required />
    </div>
    <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
        Name should not 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" name="ADDRESS" [(ngModel)]="STAP.ADDRESS" #ADDRESS="ngModel" required ></textarea>
    </div>
    <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">
        Address should not blank.
    </span>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4">HOBBY</label>
    <div class="col-lg-4">
       <div class="form-control"  style="height:110px; list-style-type: none;" >
           <li *ngFor="let c of STAP.HLIST">
            <input type="checkbox" name={{c.HID}} #HLIST="ngModel"  value={{c.HID}} [(ngModel)]=c.STATUS/>{{c.HNAME}}
           </li>
       </div>
    </div>
   <span style="color:red">{{errMessage}}</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 (keyup)="cvalidation()"  type="password" class="form-control" name="PASSWORD" [(ngModel)]="STAP.PASSWORD" #PASSWORD="ngModel" required >
    </div>
    <span class="help-block" *ngIf="PASSWORD.invalid && PASSWORD.touched">
        Password should not 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" value="Male"  name="GENDER" [(ngModel)]="STAP.GENDER" #GENDER="ngModel" required >Male
        <input  type="radio" value="Female"  name="GENDER" [(ngModel)]="STAP.GENDER" #GENDER="ngModel" required >Female
    </div>
    <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">
        Please select a gender.
    </span>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4">ARE YOU MARRIED ?</label>
    <div class="col-lg-4">
        <input  type="checkbox"  name="ISMARRIED" [(ngModel)]="STAP.ISMARRIED" #ISMARRIED="ngModel">
     
    </div>
 
</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" (change)="fillddl()" [(ngModel)]="STAP.CID" #CID="ngModel">
        <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)]="STAP.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"  style="width:80px" class="btn btn-primary" value="Save" (click)="save(stapForm.invalid)" />
        <input type="button" style="width:80px" class="btn btn-primary" value="Update" (click)="update(stapForm.invalid)" />
        <input type="button" style="width:80px" class="btn btn-primary" value="Reset" (click)="reset()" />
    </div>
</div>
<div class="form-group">
    <label class="control-label col-lg-4"></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>EID</th>
                    <th>NAME</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list">
                    <td>{{c.STID}}</td>
                    <td>{{c.NAME}}</td>
                    <td>
                        <a (click)="edit(c.STID)">Edit</a> |
                        <a (click)="del(c.STID)">Delete</a>
                    </td>
                </tr>
            </tbody>

        </table>
    </div>
</div>

</form>

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();
    }
  }
}