Sunday, 17 February 2019

CRUD operation in Angular6 & dot net core web api 2.2



web api 2.2 :

First install  some  nugget package  for EDMX.



Tools > NuGet Package Manager -> Package Manager Console

Install-Package Microsoft.EntityFrameworkCore

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

after install above

Go to Tools –> NuGet Package Manager –> Package Manager Console
And then run the following command to create a model from the existing database:
 Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Sankar;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DAL


after that add connection string in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DevConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Mahadev;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

call this connection & Enable CORS in startup.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebApplication3.DAL;

namespace WebApplication3
{
    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<MahadevContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

            services.AddCors(options =>
            {
                options.AddPolicy("EmpOrigin",
                    builder => builder.WithOrigins("*")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    );
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("EmpOrigin");
            app.UseMvc();
        }
    }
}

Then adding enable CORS attribute in web api controller :

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 Microsoft.EntityFrameworkCore;
using WebApplication3.DAL;

namespace WebApplication3.Controllers
{
    [EnableCors("EmpOrigin")]
    [Route("api/[controller]")]
    [ApiController]
    public class EmpsController : ControllerBase
    {
        private readonly MahadevContext _context;

        public EmpsController(MahadevContext context)
        {
            _context = context;
        }

        // GET: api/Emps
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Emp>>> GetEmp()
        {
            return await _context.Emp.ToListAsync();
        }

        // GET: api/Emps/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Emp>> GetEmp(int id)
        {
            var emp = await _context.Emp.FindAsync(id);

            if (emp == null)
            {
                return NotFound();
            }

            return emp;
        }

        // PUT: api/Emps/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutEmp(int id, Emp emp)
        {
            if (id != emp.Eid)
            {
                return BadRequest();
            }

            _context.Entry(emp).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmpExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Emps
        [HttpPost]
        public async Task<ActionResult<Emp>> PostEmp(Emp emp)
        {
            _context.Emp.Add(emp);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (EmpExists(emp.Eid))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction("GetEmp", new { id = emp.Eid }, emp);
        }

        // DELETE: api/Emps/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Emp>> DeleteEmp(int id)
        {
            var emp = await _context.Emp.FindAsync(id);
            if (emp == null)
            {
                return NotFound();
            }

            _context.Emp.Remove(emp);
            await _context.SaveChangesAsync();

            return emp;
        }

        private bool EmpExists(int id)
        {
            return _context.Emp.Any(e => e.Eid == id);
        }
    }
}

Angularjs 6 code :

angular model 

export class CTANGI {
    EID: number;
    NAME: string;
}


export class CTANGI1 {
    eid: number;
    name: string;
}


Angular service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders  } from '@angular/common/http';
import { CTANGI, CTANGI1 } from './tangi.model' ;
import 'rxjs/add/operator/toPromise';

@Injectable()
export class TangiServices {
    baseUrl = 'http://localhost:2300/api/Emps';
    constructor(private http: HttpClient) {
    }
    Gets(): Promise<CTANGI[]> {
        return this.http.get<CTANGI[]>(`${this.baseUrl}`)
        .toPromise();
    }
    Get(eid: number): Promise<CTANGI1> {
        return this.http.get<CTANGI1>(`${this.baseUrl}/${eid}`)
        .toPromise();
    }
    Save(emp: CTANGI): Promise<any>  {
        return this.http.post<any>(`${this.baseUrl}`
        , JSON.stringify(emp)
        , {headers : new HttpHeaders({'Content-Type': 'application/json' })})
        .toPromise();
    }
    Update(emp: CTANGI): Promise<any> {
        return this.http.put<any>(`${this.baseUrl}/${emp.EID}`
        , JSON.stringify(emp)
        , {headers : new HttpHeaders({'Content-Type': 'application/json' })})
        .toPromise();
    }
    Delete(eid: number): Promise<any> {
        return this.http.delete<any>(`${this.baseUrl}/${eid}`
        , {headers : new HttpHeaders({'Content-Type': 'application/json' })})
        .toPromise();
    }

}

Angular list view HTML :


<div class="form-group">
    <div class="col-lg-4">
        <input type="button" class="btn btn-primary" value="Add New" (click)="addnew()">
    </div>
    <label class="col-lg-4 control-label">&nbsp;</label>
</div> <br><br> 
<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>Sl No.</th>
                  <th>NAME</th>
                  <th>ACTION</th>
              </tr>
          </thead>
          <tbody>
              <tr *ngFor="let c of list;let i=index">
                  <td>{{i+1}}</td>
                  <td>{{c.name}}</td>
                  <td>
                      <a [routerLink]="['/create',c.eid]">Edit</a> |
                      <a (click)="del(c.eid)">Delete</a>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
</div>

angular List component code :

import { Component, OnInit } from '@angular/core';
import { TangiServices } from './tangi.services';
import { CTANGI } from './tangi.model';
import { Router } from '@angular/router';

@Component({
  selector: 'app-listtangi',
  templateUrl: './listtangi.component.html',
  styleUrls: ['./listtangi.component.css']
})
export class ListtangiComponent implements OnInit {
list: CTANGI[];
  constructor(private ts: TangiServices, private rou: Router) { }

  ngOnInit() {
    this.fill();
  }
  addnew(): void {
this.rou.navigate(['/create']);
  }
fill(): void {
  this.ts.Gets().then(data => {
    this.list = data;
  });
}
del(id: number): void {
if (confirm('Do you want to delete it ?') ) {
  this.ts.Delete(id).then(data => {
    alert('Data Deleted.');
    this.fill();
  });
}
}
}

Create view html:

<form class="form-horizontal" #frmTangi="ngForm">
    <div class="form-group" [class.has-error]="EID.invalid && EID.touched" [class.has-success]="EID.valid">
        <label class="col-lg-4 control-label">EID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="EID" #EID="ngModel" [(ngModel)]="TANGI.EID" required />
        </div>
        <span class="help-block" *ngIf="EID.invalid && EID.touched">
            Eid should not be blank.
        </span>
    </div>
    <div class="form-group " [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
        <label class="col-lg-4 control-label">NAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="NAME" #NAME="ngModel" [(ngModel)]="TANGI.NAME" required />
        </div>
        <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
            Name should not be blank.
        </span>
    </div>
    <div class="form-group">
        <label class="col-lg-4 control-label"></label>
        <div class="col-lg-4">
            <input type="button" class="btn btn-primary" value="Submit" style="width:80px" (click)="save()" />
            <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()" /><br>
            <a [routerLink]="['/list']">Back To List</a>
        </div>
    </div>
</form>

Create component code :

import { Component, OnInit, ViewChild } from '@angular/core';
import { CTANGI } from './tangi.model';
import { TangiServices } from './tangi.services';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-createtangi',
  templateUrl: './createtangi.component.html',
  styleUrls: ['./createtangi.component.css']
})
export class CreatetangiComponent implements OnInit {
TANGI: CTANGI;
list: CTANGI[];
id: number;
@ViewChild('frmTangi') public frmEmp: NgForm;
  constructor(private ts: TangiServices, private ac: ActivatedRoute, private ROU: Router) {
     this.id = this.ac.snapshot.params['id'];
  }
  ngOnInit() {
    this.CLR();
    this.ts.Get(this.id).then(data => {
      this.TANGI.EID = data.eid;
      this.TANGI.NAME = data.name;
    });
  }
CLR(): void {
  this.TANGI = {
     EID: null,
     NAME: null
  };

}
reset(): void {
  this.frmEmp.reset();
  this.id = undefined;
}
save(): void {
  if ( this.id === undefined) {
    this.ts.Save(this.TANGI).then(data => {
      alert('Data Saved.');
      this.frmEmp.reset();
      this.ROU.navigate(['list']);
      });
  } else {
    this.ts.Update(this.TANGI).then(data => {
      alert('Data Updated.');
      this.frmEmp.reset();
      this.ROU.navigate(['list']);
      });
  }
}
}

angular Route code :

const appRoutes: Routes = [
  { path: 'list', component: ListtangiComponent },
  { path: 'create/:id', component: CreatetangiComponent },
  { path: 'delete/:id', component: DeletemahaComponent },
  { path: 'create', component: CreatetangiComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: '**', component: PagenotfoundComponent }
];





No comments:

Post a Comment