{{announcement.body}}
{{announcement.title}}

Angular 4 and .NET Core 2.0 CRUD Operation

DZone 's Guide to

Angular 4 and .NET Core 2.0 CRUD Operation

In this post, we will add different Angular component classes to do the CRUD operation using the API last time. Let's get to it!

· Web Dev Zone ·
Free Resource

This post is the second post for our Angular 4 + Core 2.0 CRUD operations series.

In my previous post (Part I), I explained how to use the database first approach in .NET Core 2.0 and we created an Employee Web API using this approach.

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

Let's 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 the Angular component pages (whole class here). For example:

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

Add Employee Folder

Add an Employee folder into the ClientApp folder as shown below:

Get Employees

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

For this, we will follow the below steps:

  • Add EmployeeService to the TypeScript file.
  • Add Employee to the HTML file.
  • Add an Employee component class.
  • Add EmployeeComponent to the AppModule.
  • Add Employee Management to the Navigation Menu.

Add EmployeeService to the TypeScript File

We will add EmployeeService to our TypeScript file. located in the Employee folder.

Add the below code in the EmployeeService.ts class:

// Importing the libraries
import {
    Injectable
} from "@angular/core";
import {
    Http,
    Response,
    Headers
} from "@angular/http";
import "rxjs/add/operator/map";
import 'rxjs/add/operator/do'; // debug
import {
    Observable
} from "rxjs/Observable";
import {
    BehaviorSubject
} from 'rxjs/BehaviorSubject';
// To inject the dependancies in the service
@Injectable()
export class EmployeeService {
    public employeeList: Observable < Employee[] > ;
    private _employeeList: BehaviorSubject < Employee[] > ;
    private baseUrl: string;
    private dataStore: {
        employeeList: Employee[];
    };

    //// Constructor to set the values
    constructor(private http: Http) {
        // Base URL for the API
        this.baseUrl = '/api/';
        this.dataStore = {
            employeeList: []
        };
        this._employeeList = < BehaviorSubject < Employee[] >> new BehaviorSubject([]);
        this.employeeList = this._employeeList.asObservable();
    }

    // Method to get all employees by calling /api/GetAllEmployees
    getAll() {
        this.http.get(`${this.baseUrl}GetAllEmployees`)
            .map(response => response.json())
            .subscribe(data => {
                this.dataStore.employeeList = data;
                // Adding newly added Employee in the list
                this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
            }, error => console.log('Could not load employee.'));
    }
}

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

Add Employee to the HTML File

Add the below HTML code to the file:

<div id="summary" class="section panel panel-primary">
    <div class="panel-heading"> Employee Summary</div>
    <div class="container">
        <!--{{employeeList | json}}-->
        <table class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>City</th>
                    <th>Country</th>
                    <th></th>
                </tr>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
            <tbody *ngFor="let item of employeeList | async">
                <tr>
                    <td>
                        <input type="text" [(ngModel)]='item.empName' />
                    </td>
                    <td>
                        <input type="text" [(ngModel)]='item.empAge' />
                    </td>
                    <td>
                        <input type="text" [(ngModel)]='item.empCity' />
                    </td>
                    <td>
                        <input type="text" [(ngModel)]='item.empCountry' />
                    </td>
                    <td></td>
                    <td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

Here we have used:

  • ngFor to use a for loop in the Employee list.
  • Bound the Employee model to the component.

Add the Employee Component Class

Add the below code in the component class:

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/catch';
import { EmployeeService } from "./employeeService";
import { Observable } from "rxjs/Observable";
import { Employee } from "./employeeService"

//Here we specified the provider as EmployeeService and html path which we will add later
@Component({
    selector: 'employee',
    providers: [EmployeeService],
    templateUrl: './employee.component.html'
})

//After that add below code which will be used to get the data from the service
export class EmployeeComponent implements OnInit {
    public employeeList: Observable < Employee[] > ;
    showEditor = true;
    myName: string;
    employee: Employee;
    constructor(private dataService: EmployeeService) {
        this.employee = new Employee();
    }
    ngOnInit() {
        // if you want to debug info just uncomment the console.log lines.
        // console.log("You are in ngOnInit");
        this.employeeList = this.dataService.employeeList;
        this.dataService.getAll();
    }
}

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

Add EmployeeComponent to the AppModule

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

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { EmployeeComponent } from './components/Employee/employee.component'; // Added EmployeeComponent here

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        EmployeeComponent // Added EmployeeComponent here
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([{
                path: '',
                redirectTo: 'home',
                pathMatch: 'full'
            },
            {
                path: 'employee',
                component: EmployeeComponent
            }, // Added EmployeeComponent here
            {
                path: 'home',
                component: HomeComponent
            },
            {
                path: 'counter',
                component: CounterComponent
            },
            {
                path: 'fetch-data',
                component: FetchDataComponent
            },
            {
                path: '**',
                redirectTo: 'home'
            }
        ])
    ]
})
export class AppModuleShared {}

Add Employee Management in the Navigation Menu

Update Navigation menu and add the Employee link as below:

<div class='main-nav'>
    <div class='navbar navbar-inverse'>
        <div class='navbar-header'>
            <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
                <span class='sr-only'>Toggle navigation</span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
            </button>
            <a class='navbar-brand' [routerLink]="['/home']">NeelAngular4CRUD</a></div>
        <div class='clearfix'></div>
        <div class='navbar-collapse collapse'>
            <ul class='nav navbar-nav'>
                <li [routerLinkActive]="['link-active']">
                    <a [routerLink]="['/employee']">
                        <span class='glyphicon glyphicon-employee'></span> Employee Management
                    </a>
                </li>
                <li [routerLinkActive]="['link-active']">
                    <a [routerLink]="['/home']">
                        <span class='glyphicon glyphicon-home'></span> Home
                    </a>
                </li>
                <li [routerLinkActive]="['link-active']">
                    <a [routerLink]="['/counter']">
                        <span class='glyphicon glyphicon-education'></span> Counter
                    </a>
                </li>
                <li [routerLinkActive]="['link-active']">
                    <a [routerLink]="['/fetch-data']">
                        <span class='glyphicon glyphicon-th-list'></span> Fetch data
                    </a>
                </li>
            </ul>
        </div>
    </div>
</div>

Let's Test Our Changes

Run the application and click on Employee Management: As you can see, all the data that is in the database is displayed here.

Add, Update, and Delete Employees

As we can see 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:

<button class="btn btn-xs btn-primary">Update</button>

<button class="btn btn-xs btn-primary">Remove</button>

as shown below:

Changes in Employee Service for Add, Update, Delete

For adding:

public addEmployee(employee: Employee) {
    console.log("add Employee");
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    console.log('add Employee : ' + JSON.stringify(employee));

    this.http.post(`${this.baseUrl}AddEmployee/`, JSON.stringify(employee), {
            headers: headers
        })
        .map(response => response.json()).subscribe(data => {
            this.dataStore.employeeList.push(data);
            this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
        }, error => console.log('Could not create todo.'));
};

For Updating:

public updateEmployee(newEmployee: Employee) {
    console.log("update Employee");
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    console.log('Update Employee : ' + JSON.stringify(newEmployee));

    this.http.put(`${this.baseUrl}UpdateEmployee/`, JSON.stringify(newEmployee), {
            headers: headers
        })
        .map(response => response.json()).subscribe(data => {
            alert("hi");
            this.dataStore.employeeList.forEach((t, i) => {
                if (t.studentId === data.id) {
                    this.dataStore.employeeList[i] = data;
                }
            });
        }, error => console.log('Could not update todo.'));
};

For Deleting:

removeItem(employeeId: number) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    console.log("removeItem:" + employeeId);
    this.http.delete(`${this.baseUrl}DeleteEmployee/${employeeId}`, {
        headers: headers
    }).subscribe(response => {
        this.dataStore.employeeList.forEach((t, i) => {
            if (t.studentId === employeeId) {
                this.dataStore.employeeList.splice(i, 1);
            }
        });

        this._employeeList.next(Object.assign({}, this.dataStore).employeeList);
    }, error => console.log('Could not delete Employee.'));
}

Changes in Employee Component for Add, Update, Delete

For Adding:

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

For Updating:

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

For Deleting:

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

This is it!

Let's first test the Add methods:

Add the details as shown below and click on Add:

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

Same with Update, once you update something inline and click on Update, the row will be updated along with the database:

The database would also be reflected as shown below:

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

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

Hope this helps.


If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8.

Topics:
web dev ,tutorial ,.net core ,angular 4 ,crud operations

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}