Angular

You can find all of my .NET Core posts here and the source code of my sample application here.

This post is Part Two of the articles on Angular 4 + Core 2.0 CRUD operations.

In my previous post (Part I), I explained how to do Database first in .NET Core 2.0 and we created Employee Web API using Database First approach. This, you can find here.

In this post, we will add different Angular component classes to perform the CRUD operation using an API that we created in this post and will show the details on UI as shown below.

Angular

Let us start.

Set routes for API methods

Our first task is to change the routes in API methods so that it would be easier for us to give the path to Angular component pages (Whole class here). For example:

  1. [Route("~/api/GetAllEmployees")] // Add routes in all the methods
  2. [HttpGet]
  3. public IEnumerable GetEmployees() {
  4. return _context.Employees;
  5. }

Add Employee Folder

Add Employee folder on the ClientApp folder, as shown below.

Angular

Get Employees

Let us first add the code to get all employees and later, we will add the code for Add, Update, Delete.

For this, we will follow these steps.

Add EmployeeService TypeScript file

We will add EmployeeService TypeScript file under Employee folder. Add the below code in the EmployeeService.ts class:

  1. // Importing the libraries
  2. import {
  3. Injectable
  4. } from "@angular/core";
  5. import {
  6. Http,
  7. Response,
  8. Headers
  9. } from "@angular/http";
  10. import "rxjs/add/operator/map";
  11. import 'rxjs/add/operator/do'; // debug
  12. import {
  13. Observable
  14. } from "rxjs/Observable";
  15. import {
  16. BehaviorSubject
  17. } from 'rxjs/BehaviorSubject';
  18. // To inject the dependancies in the service
  19. @Injectable()
  20. export class EmployeeService {
  21. public employeeList: Observable < Employee[] > ;
  22. private _employeeList: BehaviorSubject < Employee[] > ;
  23. private baseUrl: string;
  24. private dataStore: {
  25. employeeList: Employee[];
  26. };
  27. //// Constructor to set the values
  28. constructor(private http: Http) {
  29. // Base URL for the API
  30. this.baseUrl = '/api/';
  31. this.dataStore = {
  32. employeeList: []
  33. };
  34. this._employeeList = < BehaviorSubject < Employee[] >> new BehaviorSubject([]);
  35. this.employeeList = this._employeeList.asObservable();
  36. }
  37. // Method to get all employees by calling /api/GetAllEmployees
  38. getAll() {
  39. this.http.get(`${this.baseUrl}GetAllEmployees`).map(response => response.json()).subscribe(data => {
  40. this.dataStore.employeeList = data;
  41. // Adding newly added Employee in the list
  42. this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
  43. }, error => console.log('Could not load employee.'));
  44. }
  45. }

As you can see in the above code, we are getting all the employees by calling /api/GetAllEmployees.

Add Employee HTML file

Add the below HTML code to the file.

  1. <div id="summary" class="section panel panel-primary">
  2. <div class="panel-heading"> Employee Summary</div>
  3. <div class="container">
  4. <!--{{employeeList | json}}-->
  5. <table class="table table-striped table-condensed">
  6. <thead>
  7. <tr>
  8. <th>Name</th>
  9. <th>Age</th>
  10. <th>City</th>
  11. <th>Country</th>
  12. <th></th>
  13. </tr>
  14. <tr>
  15. <th></th>
  16. <th></th>
  17. <th></th>
  18. <th></th>
  19. <th></th>
  20. <th></th>
  21. </tr>
  22. </thead>
  23. <tbody *ngFor="let item of employeeList | async">
  24. <tr>
  25. <td><input type="text" [(ngModel)]='item.empName' /></td>
  26. <td><input type="text" [(ngModel)]='item.empAge' /></td>
  27. <td><input type="text" [(ngModel)]='item.empCity' /></td>
  28. <td><input type="text" [(ngModel)]='item.empCountry' /></td>
  29. <td></td>
  30. <td>
  31. </tr>
  32. </tbody>
  33. </table>
  34. </div>
  35. </div>

Here, we have used,

Add Employee component class

Add the below code in the component class.

  1. import {
  2. Component,
  3. OnInit
  4. } from '@angular/core';
  5. import 'rxjs/add/operator/catch';
  6. import {
  7. EmployeeService
  8. } from "./employeeService";
  9. import {
  10. Observable
  11. } from "rxjs/Observable";
  12. import {
  13. Employee
  14. } from "./employeeService"
  15. //Here we specified the provider as EmployeeService and html path which we will add later
  16. @Component({
  17. selector: 'employee',
  18. providers: [EmployeeService],
  19. templateUrl: './employee.component.html'
  20. })
  21. //After that add below code which will be used to get the data from the service
  22. export class EmployeeComponent implements OnInit {
  23. public employeeList: Observable < Employee[] > ;
  24. showEditor = true;
  25. myName: string;
  26. employee: Employee;
  27. constructor(private dataService: EmployeeService) {
  28. this.employee = new Employee();
  29. }
  30. ngOnInit() {
  31. // if you want to debug info just uncomment the console.log lines.
  32. // console.log("You are in ngOnInit");
  33. this.employeeList = this.dataService.employeeList;
  34. this.dataService.getAll();
  35. }
  36. }

As you can see in the above code, we have specified that the application should call GetAll method of the service on init.

Add EmployeeComponent in the ApModule

Add EmployeeComponent to the class app.shared.module.ts, as shown below.

  1. import {
  2. NgModule
  3. } from '@angular/core';
  4. import {
  5. CommonModule
  6. } from '@angular/common';
  7. import {
  8. FormsModule
  9. } from '@angular/forms';
  10. import {
  11. HttpModule
  12. } from '@angular/http';
  13. import {
  14. RouterModule
  15. } from '@angular/router';
  16. import {
  17. AppComponent
  18. } from './components/app/app.component';
  19. import {
  20. NavMenuComponent
  21. } from './components/navmenu/navmenu.component';
  22. import {
  23. HomeComponent
  24. } from './components/home/home.component';
  25. import {
  26. FetchDataComponent
  27. } from './components/fetchdata/fetchdata.component';
  28. import {
  29. CounterComponent
  30. } from './components/counter/counter.component';
  31. import {
  32. EmployeeComponent
  33. } from './components/Employee/employee.component'; // Added EmployeeComponent here
  34. @NgModule({
  35. declarations: [
  36. AppComponent,
  37. NavMenuComponent,
  38. CounterComponent,
  39. FetchDataComponent,
  40. HomeComponent,
  41. EmployeeComponent // Added EmployeeComponent here
  42. ],
  43. imports: [
  44. CommonModule,
  45. HttpModule,
  46. FormsModule,
  47. RouterModule.forRoot([{
  48. path: '',
  49. redirectTo: 'home',
  50. pathMatch: 'full'
  51. }, {
  52. path: 'employee',
  53. component: EmployeeComponent
  54. }, // Added EmployeeComponent here
  55. {
  56. path: 'home',
  57. component: HomeComponent
  58. }, {
  59. path: 'counter',
  60. component: CounterComponent
  61. }, {
  62. path: 'fetch-data',
  63. component: FetchDataComponent
  64. }, {
  65. path: '**',
  66. redirectTo: 'home'
  67. }
  68. ])
  69. ]
  70. })
  71. export class AppModuleShared {}

Add Employee Management in the Navigation Menu

Update Navigation menu and add the Employee link as below.

  1. <div class='main-nav'>
  2. <div class='navbar navbar-inverse'>
  3. <div class='navbar-header'> <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
  4. <span class='sr-only'>Toggle navigation</span>
  5. <span class='icon-bar'></span>
  6. <span class='icon-bar'></span>
  7. <span class='icon-bar'></span>
  8. </button> <a class='navbar-brand' [routerLink]="['/home']">NeelAngular4CRUD</a></div>
  9. <div class='clearfix'></div>
  10. <div class='navbar-collapse collapse'>
  11. <ul class='nav navbar-nav'>
  12. <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/employee']">
  13. <span class='glyphicon glyphicon-employee'></span> Employee Management
  14. </a></li>
  15. <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/home']">
  16. <span class='glyphicon glyphicon-home'></span> Home
  17. </a></li>
  18. <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/counter']">
  19. <span class='glyphicon glyphicon-education'></span> Counter
  20. </a></li>
  21. <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/fetch-data']">
  22. <span class='glyphicon glyphicon-th-list'></span> Fetch data
  23. </a></li>
  24. </ul>
  25. </div>
  26. </div>
  27. </div>

Let us test our changes

Run the application and click on Employee Management.

Angular

As you can see, all the data in the database, is displayed here.

Add, Update and Delete Employees

In the list of Employees, it is time to add and update them. First of all, we will update the HTML and will add below lines:

  1. <button class="btn btn-xs btn-primary">Update</button>
  2. <button class="btn btn-xs btn-primary">Remove</button>

as shown below,

Angular

Changes in Employee Service for Add, Update, Delete

For adding:

  1. public addEmployee(employee: Employee) {
  2. console.log("add Employee");
  3. var headers = new Headers();
  4. headers.append('Content-Type', 'application/json; charset=utf-8');
  5. console.log('add Employee : ' + JSON.stringify(employee));
  6. this.http.post(`${this.baseUrl}AddEmployee/`, JSON.stringify(employee), {
  7. headers: headers
  8. }).map(response => response.json()).subscribe(data => {
  9. this.dataStore.employeeList.push(data);
  10. this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
  11. }, error => console.log('Could not create todo.'));
  12. };

For updating:

  1. public updateEmployee(newEmployee: Employee) {
  2. console.log("update Employee");
  3. var headers = new Headers();
  4. headers.append('Content-Type', 'application/json; charset=utf-8');
  5. console.log('Update Employee : ' + JSON.stringify(newEmployee));
  6. this.http.put(`${this.baseUrl}UpdateEmployee/`, JSON.stringify(newEmployee), {
  7. headers: headers
  8. }).map(response => response.json()).subscribe(data => {
  9. alert("hi");
  10. this.dataStore.employeeList.forEach((t, i) => {
  11. if (t.studentId === data.id) {
  12. this.dataStore.employeeList[i] = data;
  13. }
  14. });
  15. }, error => console.log('Could not update todo.'));
  16. };

For deleting:

  1. removeItem(employeeId: number) {
  2. var headers = new Headers();
  3. headers.append('Content-Type', 'application/json; charset=utf-8');
  4. console.log("removeItem:" + employeeId);
  5. this.http.delete(`${this.baseUrl}DeleteEmployee/${employeeId}`, {
  6. headers: headers
  7. }).subscribe(response => {
  8. this.dataStore.employeeList.forEach((t, i) => {
  9. if (t.studentId === employeeId) {
  10. this.dataStore.employeeList.splice(i, 1);
  11. }
  12. });
  13. this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
  14. }, error => console.log('Could not delete Employee.'));
  15. }

Changes in Employee Component for Add, Update, Delete

For adding:

  1. public addEmployee(item: Employee) {
  2. let todoId = this.dataService.addEmployee(this.employee);
  3. }

For updating:

  1. public updateEmployee(item: Employee) {
  2. this.dataService.updateEmployee(item);
  3. }

For deleting:

  1. public deleteEmployee(employeeId: number) {
  2. this.dataService.removeItem(employeeId);
  3. }

This is it!

Let us first test Add methods

Add the details as shown below and click on Add:

Angular

The value will be added at the end and also will be added to the database once you click on Add:

Angular

Same with Update, once you update something Inline and click on Update, the row would be updated along with the Database:

Angular

The database would also be reflected as shown below:

Angular

And to remove, just click on Remove button of the row which you want to delete:

Angular

The row would be removed from UI and the database would also get reflected:

Angular

Note
You can find the source code of my sample application here.

You can find all of my .NET Core posts here.

Hope it helps.