Thursday, 23 April 2020

CRUD operations using CORE(3.1) WEBAPI , CORE EF code first approach , ANGULAR8




CORE webapi 3.1 code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class COUNTRY
    {
        [Key]
        public int CID { get; set; }
        public string CNAME { get; set; }

    }
}

--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class STATE
    {
        [Key]
        public int SID { get; set; }
        public string SNAME { get; set; }
        public int CID { get; set; }

    }
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class HOBBY
    {
        [Key]
        public int HID { get; set; }
        public string HNAME { get; set; }
    }
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class EMP
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int EID { get; set; }
        public string NAME { get; set; }
        public string GENDER { get; set; }
        public int CID { get; set; }
        public int SID { get; set; }
    }
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class HMAP
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public int EID { get; set; }
        public int HID { get; set; }
    }
}
--

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public int EID { get; set; }
        public string NAME { get; set; }
        public string GENDER { get; set; }
        public int CID { get; set; }
        public int SID { get; set; }
        public List<int> LHOBBY { get; set; }
    }
}
--
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class AppDbContext :DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options) { }
        public DbSet<EMP> Emps { get; set; }
        public DbSet<COUNTRY> Countryies { get; set; }
        public DbSet<STATE> States { get; set; }
        public DbSet<HOBBY> Hobbies { get; set; }
        public DbSet<HMAP> Hmaps { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<COUNTRY>().HasData(
            new COUNTRY
            {
                CID = 1,
                CNAME = "X"
            });
            modelBuilder.Entity<COUNTRY>().HasData(
            new COUNTRY
            {
                CID = 2,
                CNAME = "Y"
            });
            modelBuilder.Entity<COUNTRY>().HasData(
            new COUNTRY
            {
                CID = 3,
                CNAME = "Z"
            });
            modelBuilder.Entity<STATE>().HasData(
            new STATE
            {
                SID = 1,
                SNAME = "A",
                CID=1
            });
            modelBuilder.Entity<STATE>().HasData(
           new STATE
           {
               SID = 2,
               SNAME = "B",
               CID = 1
           });
            modelBuilder.Entity<STATE>().HasData(
           new STATE
           {
               SID = 3,
               SNAME = "C",
               CID = 2
           });
            modelBuilder.Entity<STATE>().HasData(
           new STATE
           {
               SID = 4,
               SNAME = "D",
               CID = 2
           });
            modelBuilder.Entity<STATE>().HasData(
           new STATE
           {
               SID = 5,
               SNAME = "E",
               CID = 3
           });
            modelBuilder.Entity<STATE>().HasData(
           new STATE
           {
               SID = 6,
               SNAME = "F",
               CID = 3
           });
            modelBuilder.Entity<HOBBY>().HasData(
          new HOBBY
          {
              HID = 1,
              HNAME = "Cricket"
          });
            modelBuilder.Entity<HOBBY>().HasData(
         new HOBBY
         {
             HID = 2,
             HNAME = "Football"
         });
            modelBuilder.Entity<HOBBY>().HasData(
         new HOBBY
         {
             HID = 3,
             HNAME = "Baseball"
         });
            modelBuilder.Entity<HOBBY>().HasData(
         new HOBBY
         {
             HID = 4,
             HNAME = "Hockey"
         });
        }
    }
}
--

Install the following 2 NuGet packages.

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
--
After installation u add connection string in "appsettings.json"

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DbConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ApiDB;Integrated Security=True"
  }

}

--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
   public interface IDAL
    {
        Task<IEnumerable<EMP>> Gete();
        Task<IEnumerable<COUNTRY>> Getc();
        Task<IEnumerable<STATE>> Gets(int CID);
        Task<IEnumerable<HOBBY>> Geth();
        Task<EMPVM> Get(int EID);
        Task<EMP> Save(EMPVM emp);
        Task<EMP> Update(EMPVM emp);
        Task<EMP> Delete(int EID);

    }
}

--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class DAL : IDAL
    {
        private readonly AppDbContext dbContext;
        public DAL(AppDbContext DbContext)
        {
            this.dbContext = DbContext;
        }
        public async Task<EMP> Delete(int EID)
        {
            var result = await dbContext.Emps.FirstOrDefaultAsync(m => m.EID == EID);
            if (result != null)
            {
                dbContext.Emps.Remove(result);
                await dbContext.SaveChangesAsync();
                return result;
            }
            return null;
        }

        public async Task<EMPVM> Get(int EID)
        {
            EMPVM vm =await dbContext.Emps.Select(m => new EMPVM { EID = m.EID, NAME = m.NAME, GENDER = m.GENDER, CID = m.CID, SID = m.SID }).FirstOrDefaultAsync(n=>n.EID==EID);
            vm.LHOBBY =await dbContext.Hmaps.Where(n => n.EID == EID).Select(m => m.HID).ToListAsync();
            return vm;
        }

        public async Task<IEnumerable<COUNTRY>> Getc()
        {
            return await dbContext.Countryies.ToListAsync();
        }

        public async Task<IEnumerable<EMP>> Gete()
        {
            return await dbContext.Emps.ToListAsync();
        }

        public async Task<IEnumerable<HOBBY>> Geth()
        {
            return await dbContext.Hobbies.ToListAsync();
        }

        public async Task<IEnumerable<STATE>> Gets(int CID)
        {
            return await dbContext.States.Where(m=>m.CID==CID).ToListAsync();
        }

        public async Task<EMP> Save(EMPVM vm)
        {
            EMP emp = new EMP()
            {
                EID=vm.EID,
                NAME=vm.NAME,
                GENDER=vm.GENDER,
                CID=vm.CID,
                SID=vm.SID
            };
            var result = await dbContext.Emps.AddAsync(emp);
            await dbContext.Hmaps.AddRangeAsync(vm.LHOBBY.Select(m => new HMAP { EID = vm.EID, HID = m }).ToList());
            await dbContext.SaveChangesAsync();
            return result.Entity;
        }
        public async Task<EMP> Update(EMPVM vm)
        {
            var result = await dbContext.Emps.FirstOrDefaultAsync(m => m.EID == vm.EID);
            if (result != null)
            {
                result.NAME = vm.NAME;
                result.GENDER = vm.GENDER;
                result.CID = vm.CID;
                result.SID = vm.SID;
                dbContext.Hmaps.RemoveRange(dbContext.Hmaps.Where(m => m.EID == vm.EID).ToList());
                await dbContext.Hmaps.AddRangeAsync(vm.LHOBBY.Select(m => new HMAP { EID = vm.EID, HID = m }).ToList());
                await dbContext.SaveChangesAsync();
                return result;
            }
            return null;
        }
    }
}
--
Add connection in status class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WebApplication1.Models;

namespace WebApplication1
{
    
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
            services.AddScoped<IDAL, DAL>();
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy("CORS",
                    builder => builder.WithOrigins("*")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    );
            });
            services.AddControllersWithViews()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.Converters.Add(new WebApplication1.Models.LongToStringConverter());
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseCors("CORS");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            
           

        }
    }
}

--
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class LongToStringConverter : JsonConverter<long>
    {
        public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                if (Utf8Parser.TryParse(span, out long number, out int bytesConsumed) && span.Length == bytesConsumed)
                    return number;

                if (Int64.TryParse(reader.GetString(), out number))
                    return number;
            }

            return reader.GetInt64();
        }

        public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }
}

--
Create and execute database migrations
Use the following 2 commands to create and execute the initial database migration

Add-Migration 1st
Update-Database

--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    [EnableCors("CORS")]
    [Route("api/[controller]")]
    [ApiController]
    public class EmpservicesController : ControllerBase
    {
        private readonly IDAL dal;
        public EmpservicesController(IDAL Dal)
        {
            this.dal = Dal;
        }
        [HttpGet]
        public async Task<ActionResult<IEnumerable<EMP>>> Gete()
        {
            try
            {
                return Ok(await dal.Gete());
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpGet("Getc")]    
        public async Task<ActionResult<IEnumerable<COUNTRY>>> Getc()
        {
            try
            {
                return Ok(await dal.Getc());
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);

            }
        }
        [HttpGet("Geth")]
        public async Task<ActionResult<IEnumerable<HOBBY>>> Geth()
        {
            try
            {
                return Ok(await dal.Geth());
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpGet("Gets")]
        public async Task<ActionResult<STATE>> Gets([FromQuery]int CID)
        {
            try
            {
                var result = await dal.Gets(CID);
                if (result == null)
                {
                    return NotFound();
                }
                return Ok(result);
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpGet("Get/{EID:int}")]
        public async Task<ActionResult<EMPVM>> Get(int EID)
        {
            try
            {
                var result = await dal.Get(EID);
                if (result == null)
                    return NotFound();
                return Ok(result);
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpPost]
        public async Task<ActionResult<EMP>> Save(EMPVM emp) 
        {
            try
            {
                if (emp == null)
                {
                    return BadRequest("Send a null model.");
                }
                var result = await dal.Save(emp);
                return CreatedAtAction(nameof(Get), new { EID = result.EID }, result);
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }
        [HttpPut("{EID:int}")]
        public async Task<ActionResult<EMP>> Update([FromRoute]int EID,[FromBody]EMPVM emp)
        {
            try
            {
                if (EID != emp.EID)
                {
                    return BadRequest("Employee ID mismatch.");
                }
                var result = await dal.Get(EID);
                if (result == null)
                    return NotFound($"Employee with ID = {EID} not found.");
                return await dal.Update(emp);
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }
        [HttpDelete("{EID:int}")]
        public async Task<ActionResult<EMP>> Delete(int EID)
        {
            try
            {
                var result = await dal.Get(EID);
                if (result == null)
                    return NotFound($"Employee with ID = {EID} not found.");
                return await dal.Delete(EID);
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }

    }
}
--
Angular8 code :


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 IEMP {
    EID: number;
    NAME: string;
    GENDER: string;
    CID: number;
    SID: number;
    LHOBBY: number[];
}

--
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IEMP } from '../api/api.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/observable/throw';

@Injectable()
export class ApiServices {
    constructor(private http: HttpClient) {

    }
    baseUrl = 'https://localhost:44336/api/Empservices';
    Getc() {
        return this.http.get(`${this.baseUrl}/${'Getc'}`)
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Geth() {
        return this.http.get(`${this.baseUrl}/${'Geth'}`)
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Gets(cid: number) {
        return this.http.get(`${this.baseUrl}/${'Gets?CID='}${cid}`)
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Gete() {
        return this.http.get(`${this.baseUrl}`)
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Get(eid: number) {
        return this.http.get(`${this.baseUrl}/${'Get'}/${eid}`)
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Save(emp: IEMP) {
        return this.http.post(`${this.baseUrl}`
        , JSON.stringify(emp)
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Update(eid: number, emp: IEMP) {
        return this.http.put(`${this.baseUrl}/${eid}`
        , JSON.stringify(emp)
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Delete(eid: number) {
        return this.http.delete(`${this.baseUrl}/${eid}`
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
}

--

<form class="form-horizontal" [formGroup]="frmApi">
        <div class="form-group">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4 alert-danger" *ngIf='errorMessage !== undefined'>
                  {{errorMessage}}
                </div>
        </div>
  <div class="form-group " [ngClass]="{'has-error':frmApi.get('EID').errors && (frmApi.get('EID').touched || frmApi.get('EID').dirty)}">
      <label class="col-lg-4 control-label">EID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" formControlName="EID" />
      </div>
      <span class="help-block has-error" *ngIf="frmApi.get('EID').errors && (frmApi.get('EID').touched || frmApi.get('EID').dirty)">
          <span *ngIf="frmApi.get('EID').errors.required">Eid should not be blank.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmApi.get('NAME').errors && (frmApi.get('NAME').touched || frmApi.get('NAME').dirty)}">
      <label class="col-lg-4 control-label">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" formControlName="NAME" />
      </div>
      <span class="help-block has-error" *ngIf="frmApi.get('NAME').errors && (frmApi.get('NAME').touched || frmApi.get('NAME').dirty)">
          <span *ngIf="frmApi.get('NAME').errors.required">Name should not be blank.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmApi.get('GENDER').errors && (frmApi.get('GENDER').touched || frmApi.get('GENDER').dirty)}">
      <label class="col-lg-4 control-label">GENDER</label>
      <div class="col-lg-4">
          <input type="radio"  formControlName="GENDER" value="Male" />Male
          <input type="radio"  formControlName="GENDER" value="Female" />Female
      </div>
      <span class="help-block has-error" *ngIf="frmApi.get('GENDER').errors && (frmApi.get('GENDER').touched || frmApi.get('GENDER').dirty)">
          <span *ngIf="frmApi.get('GENDER').errors.required">Please select a gender.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmApi.get('CID').errors && (frmApi.get('CID').touched || frmApi.get('CID').dirty)}">
      <label class="col-lg-4 control-label">COUNTRY</label>
      <div class="col-lg-4">
          <select class="form-control" formControlName="CID" (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 has-error" *ngIf="frmApi.get('CID').errors && (frmApi.get('CID').touched || frmApi.get('CID').dirty)">
          <span *ngIf="frmApi.get('CID').errors.required">Please select a country.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmApi.get('SID').errors && (frmApi.get('SID').touched || frmApi.get('SID').dirty)}">
      <label class="col-lg-4 control-label">STATE</label>
      <div class="col-lg-4">
          <select class="form-control" formControlName="SID">
              <option [ngValue]="null">Select</option>
              <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
          </select>
      </div>
      <span class="help-block has-error" *ngIf="frmApi.get('SID').errors && (frmApi.get('SID').touched || frmApi.get('SID').dirty)">
          <span *ngIf="frmApi.get('SID').errors.required">Please select a state.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmApi.get('LHOBBY').errors && (frmApi.get('LHOBBY').touched || frmApi.get('LHOBBY').dirty)}">
      <label class="col-lg-4 control-label">HOBBY</label>
      <div class="col-lg-4">
          <select class="form-control" formControlName="LHOBBY" multiple>
              <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
          </select>
      </div>
      <span class="help-block has-error" *ngIf="frmApi.get('LHOBBY').errors && (frmApi.get('LHOBBY').touched || frmApi.get('LHOBBY').dirty)">
          <span *ngIf="frmApi.get('LHOBBY').errors.required">Please select a hobby.</span>
      </span>
  </div>
  <div class="form-group">
      <label class="col-lg-4 control-label"></label>
      <div class="col-lg-4">
          <input type="button" value="Submit" class="btn btn-primary" style="width:80px" (click)="save(frmApi.invalid)" />
          <input type="button" value="Reset" class="btn btn-primary" style="width:80px" (click)="reset(frmApi)" />
          <a [routerLink]="['/list']" >Back To List</a>
      </div>
  </div>
</form>
--
import { Component, OnInit } from '@angular/core';
import { COUNTRY, STATE, HOBBY, IEMP } from '../api/api.model';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
import { ApiServices } from '../api/api.services';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-createapi',
  templateUrl: './createapi.component.html',
  styleUrls: ['./createapi.component.css']
})
export class CreateapiComponent implements OnInit {

  constructor(private fb: FormBuilder, private aps: ApiServices, private ro: Router, private ac: ActivatedRoute) { }
  listc: COUNTRY[];
  lists: STATE[];
  listh: HOBBY[];
  EMP: IEMP;
  frmApi: FormGroup;
  errorMessage: string;
  eid: number;
  ngOnInit() {
    this.frmApi = this.fb.group({
      EID: [null, Validators.required],
      NAME: [null, Validators.required],
      GENDER: [null, Validators.required],
      CID: [null, Validators.required],
      SID: [null, Validators.required],
      LHOBBY: [null, Validators.required]
    });
    this.CLR();
    this.aps.Getc().subscribe((data) => {
      this.listc = data;
    }, (err) => {
      this.errorMessage = err.message;
    });
    this.aps.Geth().subscribe((data) => {
      this.listh = data;
    }, (err) => {
      this.errorMessage = err.message;
    });
    this.eid = this.ac.snapshot.params['id'];
    if ( this.eid !== undefined ) {
      this.aps.Get(this.eid).subscribe( (data) => {
        this.fx(data.CID);
        this.frmApi.setValue({
          EID: data.EID,
          NAME: data.NAME,
          GENDER: data.GENDER,
          CID: data.CID,
          SID: data.SID,
          LHOBBY: data.LHOBBY
        });
      }, (err) => {
        this.errorMessage = err.message;
      });
    }
  }
  fillddl(): void {
    this.fx(this.frmApi.value.CID);
  }
  fx(cid: number): void {
    this.aps.Gets(cid).subscribe((data) => {
      this.lists = data;
    }, (err) => {
      this.errorMessage = err.message;
    });
  }
  save(isValid: boolean): void {
    if (!isValid) {
      this.EMP.EID = Number(this.frmApi.value.EID);
      this.EMP.NAME = this.frmApi.value.NAME;
      this.EMP.GENDER = this.frmApi.value.GENDER;
      this.EMP.CID = Number(this.frmApi.value.CID);
      this.EMP.SID = Number(this.frmApi.value.SID);
      this.EMP.LHOBBY = this.frmApi.value.LHOBBY;
      if ( this.eid !== undefined ) {
        this.aps.Update(this.eid, this.EMP).subscribe( (data) => {
          this.ro.navigate(['/list']);
        }, (err) => {
          this.errorMessage = err.message;
        });
      } else {
        this.aps.Save(this.EMP).subscribe( (data) => {
          this.ro.navigate(['/list']);
        }, (err) => {
          this.errorMessage = err.message;
        });
      }
    }
   }
  CLR(): void {
    this.EMP = {
      EID: null,
      NAME: null,
      GENDER: null,
      CID: null,
      SID: null,
      LHOBBY: []
    };
  }
  reset(nf: NgForm): void {
    nf.reset();
  }
}

--
<div class="row">
  <input type="button" value="Add New" class="btn btn-primary" style="width:80px" [routerLink]="['/create']" />
</div><br>
<div class="row alert-danger" *ngIf='errorMessage !== undefined'>
      {{errorMessage}}
</div>
<div class="row">
  <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|ApiPipe: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>
--

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IEMP } from '../api/api.model';
import { ApiServices } from '../api/api.services';

@Component({
  selector: 'app-listapi',
  templateUrl: './listapi.component.html',
  styleUrls: ['./listapi.component.css']
})
export class ListapiComponent implements OnInit {

  constructor(private aps: ApiServices, private ro: Router) { this.fill(); }
  list: IEMP[];
  errorMessage: string;
  ngOnInit() {
  }
  fill(): void {
    this.aps.Gete().subscribe((data) => {
      this.list = data;
    }, (err) => {
      this.errorMessage = err.message;
    });
  }
  del(eid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.aps.Delete(eid).subscribe((data) => {
        this.fill();
      }, (err) => {
        this.errorMessage = err.message;
      });
    }
  }
}
--
import {Pipe, PipeTransform } from '@angular/core';

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








No comments:

Post a Comment