CRUD Operations In ASP.NET MVC Using Angular With Basics - Part Three

This is Part 3 of "CRUD Operations in Asp MVC using Angular 2 with Basics."
 
Before starting, I will recommend you read my previous articles about Angular and its features and versions.
In our previous articles, we have added the following Angular files and controller. Please find the below image for your reference:
 
 
 
 
Now, let's add employee folder under "src/app" folder.
 
Next, add an Employee Component under Employee Folder.
 
To create
 
Select Employee Folder -> Right Click -> Add -> Select "TypeScript File"  -> Enter the name of our typescript file "Employee.Component.ts" -> Click ok
 
 
 
Now you can see, an empty employee component has been added in our employee folder. Please copy the below code and paste it in our employee component.
  1. import { Component } from '@angular/core';  // importing component from @angular/core directives
  2.   
  3. @Component({  
  4.     selector: 'emp',  //This is the selector of our section
  5.     template: '<h1>This is our Employee Component',  //HTML tag to render inside of emp selector
  6. })  
  7.   
  8. export class EmployeeComponent{  
  9.    //you can declare class properties here
  10. }  
Then next, we have to register our employee component into our root module.

Note

Our root module is app.module.ts
 
Note

We have declared our Employee component also a root component for App Module. 
  1. import { NgModule }      from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { AppComponent } from './app.component';  
  4. import {EmployeeComponent } from './Employee/EmployeeComponent'; //Importing employee component  
  5.   
  6. @NgModule({  
  7.   imports:      [ BrowserModule ],  
  8.     declarations: [AppComponent, EmployeeComponent ]//registering our employee component in declaration   
  9.   bootstrap:    [ AppComponent,EmployeeComponent ]  //declared employee component also as a root component
  10. })  
  11. export class AppModule { }  
Let's add our emp selector into our index page and run it.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <title>Angular QuickStart</title>  
  5.     <base href="/src/">  
  6.     <meta charset="UTF-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link rel="stylesheet" href="styles.css">  
  9.   
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  12.   
  13.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  14.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  15.   
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.       System.import('main.js').catch(function(err){ console.error(err); });  
  19.     </script>  
  20.   </head>  
  21.   
  22.   <body>  
  23.     <my-app>Loading AppComponent content here ...</my-app>  
  24.     <emp></emp>  
  25.   </body>  
  26. </html>   
 
The result has been displayed as we expected.
 
Here, instead of writing HTML inside employee component, let's refer to an external HTML file. To do this, first, add an HTML file inside employee folder. 
 
 
 
Modify the below code in your employee component. 
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'emp',  
  5.     templateUrl: 'app/Employee/Employee.Component.html',  //Refering the external html file
  6. })  
  7.   
  8. export class EmployeeComponent{  
  9.    
  10. }  
templateurl property is used to refer to the external HTML file. 
 
Now, let's add some properties in our employee component and display the values in our HTML page.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'emp',  
  5.     templateUrl: 'app/Employee/Employee.Component.html',  
  6. })  
  7.   
  8. export class EmployeeComponent{  
  9.     EmpId: number = 1;  
  10.     EmpName: string = "Ramesh";  
  11.     EmpAge: number = 26;  
  12.     EmpCity: string = "Bangalore";  
  13.     EmpMobileNo: string = "1234567890";  
  14. }  
Add the below HTML script into our Employee.Component.Html file
  1. <h1> This is our employee component</h1>  
  2. <table border="1">  
  3.     <thead>  
  4.         <tr>  
  5.             <td>Name</td>  
  6.             <td>Age</td>  
  7.             <td>City</td>  
  8.             <td>Mobile No</td>  
  9.         </tr>  
  10.     </thead>  
  11.     <tbody>  
  12.         <tr>  
  13.             <td>{{EmpName}}</td>  
  14.             <td>{{EmpAge}}</td>  
  15.             <td>{{EmpCity}}</td>  
  16.             <td>{{EmpMobileNo}}</td>  
  17.         </tr>  
  18.     </tbody>  
  19. </table>  
Run our project and we will see the result.
 
 
The result has been displayed as we expected. Now, let's add multiple rows in a table using *NgFor and "any" datatype.
 
Browser Module provides the *ngFor and *ngIf directives. To know more about *ngFor and *ngIf please click Here
 
*ngFor directive is used to loop the elements.
*ngIf directive is used to evaluate the conditions.
 
This directives are called structural directives. 
 
First let's add a simple interface to our employee folder. To add, select Employee folder -> Right Click -> select "Type Script File" -> enter the name of the file "IEmployee.ts" then click OK . Please, find the below image for your reference:
 
 
 
Copy the below code and paste it in our IEmployee interface. 
  1. export interface IEmployee {  
  2.     EmpId: number;  
  3.     EmpName: string;  
  4.     EmpAge: number;  
  5.     EmpCity: string;  
  6.     EmpMobileNo: string;  
  7. }  
Note

Export keyword used to export the interfaces or classes in any other compoenents and services. If we didn't mention the export keyword in our interface or class, we cannot reuse this on any other components.
 
Let's import our IEmployee interface into our Employee Component. Please find the below code for your reference.
  1. import { Component } from '@angular/core';  
  2. import { IEmployee } from './IEmployee';  
  3.   
  4. @Component({  
  5.     selector: 'emp',  
  6.     templateUrl: 'app/Employee/Employee.Component.html',  
  7. })  
  8.   
  9. export class EmployeeComponent {  
  10.     EmployeeDetails: IEmployee[];  
  11.     constructor() {   
  12.         this.EmployeeDetails = [  
  13.             { EmpId: 1, EmpName: 'Ramesh', EmpAge: 26, EmpCity: 'Bangalore', EmpMobileNo: '1234567890' },  
  14.             { EmpId: 2, EmpName: 'Kiran', EmpAge: 22, EmpCity: 'Chennai', EmpMobileNo: '1234567890' },  
  15.             { EmpId: 3, EmpName: 'Anisha', EmpAge: 29, EmpCity: 'Delhi', EmpMobileNo: '1234567890' }  
  16.         ]  
  17.     }  
  18. }  
 Let's make the chages in our HTML file and we will see the result.
  1. <h1> This is our employee component</h1>  
  2. <table border="1">  
  3.     <thead>  
  4.         <tr>  
  5.             <td>Name</td>  
  6.             <td>Age</td>  
  7.             <td>City</td>  
  8.             <td>Mobile No</td>  
  9.         </tr>  
  10.     </thead>  
  11.     <tbody >  
  12.         <tr *ngFor="let employee of EmployeeDetails">  
  13.             <td>{{employee.EmpName}}</td>  
  14.             <td>{{employee.EmpAge}}</td>  
  15.             <td>{{employee.EmpCity}}</td>  
  16.             <td>{{employee.EmpMobileNo}}</td>  
  17.         </tr>  
  18.     </tbody>  
  19. </table>  
 
You can see here, the result has been displayed as we expected. Next let's get the data from database using HTTP module and Services.
 
To create service, please follow the below steps.
 
Select Employee Folder => Right Click => Add => Select "Type Script File" => Click OK => Enter the service name "Employee.service.ts" => Click Ok. Please find the sample image for your reference.
 
 
 
Once the service has been created, copy the below code and paste it into our IEmployee.service.ts 
  1. import { Injectable} from '@angular/core'  
  2.   
  3. @Injectable()  
  4. export class EmployeeService {  
  5.   
  6. }  
Let's understand the code,
 
@Injectable is used for dependency injection. Dependency Injection (DI) is a way to create objects that depend upon other objects.
 
In Angular, if you are creating a service, I recommended adding @Injectable for future purpose. For now, we don't have any dependencies.
  
Note

We are importing "@Injectable" from @angular/core directives.
 
Let's import our IEmployee interface and Http module in our Employee service. Please find the sample code below:
  1. import { Injectable } from '@angular/core'  
  2. import {IEmployee } from './IEmployee';  
  3. import {Http,Response } from '@angular/http';  
  4.   
  5. @Injectable()  
  6. export class EmployeeService {  
  7.     constructor(private _http: Http) {  
  8.   
  9.     }  
  10. }  
Here, you can see, we have implemented the constructor for our employee service and injected the HTTP module. Here @Injectable is required to inject our HTTP Module. If you are not using @Injectable, you will get the run time exception. Please find the sample image below,
 
 
What is Http Module?
 
HTTP is a protocol which is used to communicate with the remote server. In Angular, the same HTTP module is going to be used for communicating with the server (Controller).
 
To know more about HTTP Module, please refer to the below links,
Let's add a method to communicate with the controller to get the list of records from the database. 
 
Note
We have already implemented the controller and database in our part two tutorial:
 
 
 
We have created a method "getEmployeeDetails()" to get the list of employees from the database. Used _http.get method to communicate with our GetAllEmployees action result in our Employee Controller.
 
In the above image, we can see the error message. We cannot assign the Obesevable<Response> to IEmployee[] property. 
 
The _http.get method will return an observable response. So, we have to assign our resposne to Observable<IEmployee[]>, so let's add few changes in our code:
 
 
 
Now, we have assigned our response to Observable<IEmployee[]>. Note: Observable is importing from rxjs/Observable.
 
But now, we are facing another issue  -- it's saying we cannot assign Observable<Response> to Observable<IEmployee[]>
 
To convert our Response to IEmployee[], we have an one more property called map which needs to be imported from "rxjs/add/operator/map". Let's convert Response to IEmployee[] using map. Please find the below code for your reference:
  1. import { Injectable } from '@angular/core'  
  2. import {IEmployee } from './IEmployee';  
  3. import { Http, Response } from '@angular/http';  
  4. import { Observable } from 'rxjs/Observable';  
  5. import 'rxjs/add/operator/map';  
  6.   
  7. @Injectable()  
  8. export class EmployeeService {  
  9.     constructor(private _http: Http) {  
  10.   
  11.     }  
  12.   
  13.     getEmployeeDetails(): Observable<IEmployee[]> {  
  14.         return this._http.get("http://localhost:57997/Employee/GetAllEmployees").map((response: Response) => <IEmployee[]>response.json());  
  15.     }  
  16. }  
Our service has been created successfully now. Let's use import our service in our Employee Component. 
 
Before that, let's import an HTTP module in our App.Module.ts. Please refer to the below code for your reference:
  1. import { NgModule }      from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { AppComponent } from './app.component';  
  4. import { EmployeeComponent } from './Employee/Employee.Component';  
  5. import { HttpModule } from '@angular/http';  
  6.   
  7. @NgModule({  
  8.   imports:      [ BrowserModule,HttpModule ],  
  9.     declarations: [AppComponent, EmployeeComponent ],  
  10.   bootstrap:    [ AppComponent ,EmployeeComponent]  
  11. })  
  12. export class AppModule { }  
Open our employee component, copy and paste the below code.
  1. import { Component,OnInit } from '@angular/core';  
  2. import { IEmployee } from './IEmployee';  
  3. import { EmployeeService } from './Employee.service';  
  4. @Component({  
  5.     selector: 'emp',  
  6.     templateUrl: 'app/Employee/Employee.Component.html',  
  7.     providers:[EmployeeService]  
  8. })  
  9.   
  10. export class EmployeeComponent implements OnInit {  
  11.     EmployeeDetails: IEmployee[];  
  12.     //Insjecting service in our constructor  
  13.     constructor(private _EmployeeService: EmployeeService) {  
  14.          
  15.     }  
  16.     ngOnInit() {  
  17.         //calling a method  
  18.         this.LoadEmployeeData();  
  19.     }  
  20.     //Created a method to call getEmployeeDetails method in our Employee Service.  
  21.     LoadEmployeeData() {   
  22.         this._EmployeeService.getEmployeeDetails().subscribe((employeeData) => this.EmployeeDetails = employeeData);  
  23.         //Subscribe method is used to convert our Observable response to IEmployee[] response  
  24.     }  
  25. }  
Let's understand the code step by step,
 
First import the service in our Employee.Component.ts. Then import OnInit in @angular/core.
 
Note
The OnInit method will render after the constructor. 
 
We can declare all the dependency and variable values assigned in the constructor. We can perform our custom functionality in the NgOnInit method. 
 
Use providers property use service in our Component.
 
Create constructor and inject our EmployeeService.  Then create a method "LoadEmployeeDate" to call the service method "getEmployeeDetails"
 
Note
The subscribe method is used to convert our Observable<IEmployee[]> response to IEmployee[] 
 
In ngOnInit method, let's call the method "LoadEmployeeData()". Save and Run our project.
 
 
The result has been displayed as we expected. In our next article, let's perform Add, Update and Delete operations using Angular. 
 
Please give your valuable comments to improve my article writing. Thanks.


Similar Articles