Angular 5 Simple Program with CRUD Operation Example using PHP RESTFull API

In this blog we will develop simple program in angular 5 which will perform CRUD Operation consuming WebAPI . Angular 5 is a google framework and successor of highly popular and efficient framework AngularJS . It is successor of AngularJS but it is not all similar with angular JS . As due to the advance development in Web Technologies And New real time problem scenario Angular 2 was introduce as a new framework . There is no need to learn angularJS to start with angular 5 . You can directly start learning angular 5 . Angular 5 Uses typescript framework to make development really fast and gives javascript type definition which was not possible earlier . Typescript is a compiler used to compile typescript file in JAVASCRIPT file . Most beautiful part of typescript is that you can write javascript code also in typescript it will compile and runs as usual . We will using Angular for angular 5 so dont get confused. To more About Tyscript and its Syntax you should look at this website . In angular 5 you can develop Native Mobile Application using Nativescript .You Can make SEO Friendly Application in angular 5 using Angular Universal which is not possible in AngularJS . Just Code once and you can create both application from one source code .

https://nodejs.org/en/

Task

We Will be performing Student details system task . To know more about task you can refer to this webiste

 

Requirement

  1. Visual Studio Code (you can find help here)
  2. CRUD RESTFull Web API in PHP . You can develop your own by following this link
  3. NodeJS runtime to install different Modules . You can download and install from here .

 

Installation

  1. Open Visual Studio Code and start its inbuilt terminal by typing (~+ctrl)
  2. Type npm install -g @angular/cli this is used to install angular command line interface of (CLI) It will benefial for creating different component and services .
  3. Type ng new my-app this is used to create new application .you can Provide your name at my-app . We will giving name as student-details
  4. cd student-details
  5. Type npm install
  6. ng serve to start your basic application

To Learn more its structure and variable you can found it here . In my suggestion just give it a look .

 

 

Angulars main building blocks are shown above . We will be using default app module and default app component for our application . You can create and different modules and component on your requirement as you like . we will be covering and discussing different modules and component in our coming examples . Lets get started our default structure which is created by angular CLI for us . Hope you have gone through the structure if not kindly go through this link for structure understanding .

 

As you can see in the link we will be only changing app.component.ts for writing typescript code and app.component.html , app.component.css for writing template in angular .

 

In app.component.html delete all stuff generated by angular cli . paste the following code .

To Start Two Way binding in angular 5 you need to import FormModule in app.module.ts . Following is full app.module.ts file code

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

 

You have to add

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

In index.html after title to use W3.css in your angular 5

 

Now just Add following code on app.component.html .

<div style="width:100%;text-align:center"> <h1> Student Detail System</h1> </div> <div style="width:100%;align-content: center"> <div style="margin:10px;display: inline-block;">
Name :<input name="Name" type="text" [(ngModel)]="Name" ></div> <div style="margin:10px;display: inline-block;">
Address :<input name="Address" type="text" [(ngModel)]="Address"></div> <div style="margin:10px;display: inline-block;">
Telephone :<input name="Telephone" type="text" [(ngModel)]="Telephone"></div> <div style="margin:10px;display: inline-block;">
Standard :<input name="Standard" type="text" [(ngModel)]="Standard"></div> <div style="margin:10px;display: inline-block;" >
Roll Number :<input name="RollNumber" type="text" [(ngModel)]="RollNumber"></div> </div> <div class="w3-cell-row w3-center w3-padding"> <input name="submit" [click]="Insert()"
class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Insert"/> <input name="Update" [click]="Update()"
class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Update"/> <input name="Delete" [click]="Delete()"
class="w3-btn w3-blue w3-border w3-margin" type="submit" value="Delete"/> </div> <table class="w3-table-all w3-small "> <tr > <td [hidden]="true">Student_ID</td> <td>Name</td> <td>Address</td> <td>Telephone</td> <td>Standard</td> <td>Roll Number</td> <td>Update / Delete</td> </tr> <tr *ngFor="let item of items" class='w3-hover-blue' style='cursor:pointer;'> <td [hidden]="true">{{item.student_id}}</td> <td>{{item.Name}}</td> <td>{{item.Address}}</td> <td>{{item.Telephone}}</td> <td>{{item.Standard}}</td> <td>{{item.Roll_Number}}</td> <td><button [click]="Select($index)" >Select</button></td> </tr>

 

PHP RESTFull Web API Details

 

For Creating Restfull Web Api you have to follow this article to create one for you on your computer . After Following given blog you will have 5 web apis to consume in your Angular 5 Application . It will be

 

 

  1. INSERT OPERATION
  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Insert, Name=Can be any,Address=Can be any ,Telephone=Can be any , Standard=Can be any ,Roll_Number=Can be any}

 

2.UPDATE OPERATION

 

  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : : { Type=Update,student_id=Of Changing Record, Name=Can be any',Address=Can be any ,Telephone=Can be any, Standard=Can be any ,Roll_Number=Can be any}

 

3.SEARCH OPERATION

 

  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Search ,student_id=Of Record }

 

4.GETALLRECORDS.

 

  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=GetAllRecords }

 

5.DELETE OPERATION

 

  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Delete ,student_id=Of Record }

 

You can even use POSTMAN to check your JSON Response .

Angular 5 uses for Observable for http calls to fetch and post data to the server . Observable is technique used for async calls . It can be considered as event emitter and data collection . It is not New in Programming . It was already in use angular uses its because of its flexible nature. You can consider observable as a stream of data generated by observable which is passed to its subscriber as the time passes and as that observable generates data . It is huge and vast topic which we will explain in coming blogs . It is actually the replacement of promise which we use to handle asynchronous data in JAVASCRIPTING.

 

To Make Asynchronous call you have create new service which will handle all your http Request and provide you with data . In this way you will separated your MODEL from your logic layer . To Use Observable first you need to create models in your applications . You need to create classes with parameters name same as JSON Parameter . For Our JSON Requests we have to created following Class to get data .

 

Paste this comment to create new class in your angular 5 application using angular cli

 

 

ng g class Data

In data.ts paste following code

Data.ts

 

 

export class Data { public student_id:number ; public Name:string ; public Addres:string ; public Telephone:string; public Standard:string; public Roll_Number:string ; }

 

 

 

ng g class Response

In response.ts paste following code

Response.ts

 

 

import { Data } from './data'; export class Response { public status :number; public data:Data[]; }

Response1.ts

 

import { Data } from './data'; export class Response1 { public status :number; public data:Data; }

We have created different Class because we have different response from Search API . We will discuss later in this blog .

Now You need to create Different Service to handle all http calls . As it is good practice to keep business logic separate from data fetching task and data models . It makes our work much more easy and efficient . To create new service you need to run following command in Terminal in visual studio code integrated terminal .

ng g service httpcall

It will create service with file src/app/httpcall.service.ts . You need to modify this file for fetching data from RESTFULL Web API . Copy paste following code

import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { Response } from './response'; import { Data } from './data'; import { Response1 } from './Response1'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class HttpcallService { constructor(private http:HttpClient) { } getAllStudents() : Observable<Response> { var headers = new HttpHeaders(); headers.append('Content-Type', 'application/form-data'); const fd = new FormData(); fd.append('Type', 'GetAllRecords'); return this.http.post<Response>("http://localhost:8080/StudentApi/",fd, {headers: headers } ); } InsertStudents(data:Data) : Observable<Response> { var headers = new HttpHeaders(); headers.append('Content-Type', 'application/form-data'); const fd = new FormData(); fd.append('Type', 'Insert'); fd.append('Name', data.Name); fd.append('Address', data.Addres); fd.append('Telephone', data.Telephone); fd.append('Standard', data.Standard); fd.append('Roll_Number', data.Roll_Number); return this.http.post<Response>("http://localhost:8080/StudentApi/",fd, {headers: headers } ); } UpdateStudents(data:Data) : Observable<Response> { var headers = new HttpHeaders(); headers.append('Content-Type', 'application/form-data'); const fd = new FormData(); fd.append('Type', 'Update'); fd.append('Name', data.Name); fd.append('Address', data.Addres); fd.append('Telephone', data.Telephone); fd.append('Standard', data.Standard); fd.append('Roll_Number', data.Roll_Number); fd.append('student_id', data.student_id.toString()); return this.http.post<Response>("http://localhost:8080/StudentApi/",fd, {headers: headers } ); } DeleteStudents(data:Data) : Observable<Response> { var headers = new HttpHeaders(); headers.append('Content-Type', 'application/form-data'); const fd = new FormData(); fd.append('Type', 'Delete'); fd.append('student_id', data.student_id.toString()); return this.http.post<Response>("http://localhost:8080/StudentApi/",fd, {headers: headers } ); } SearchStudents(data:Data) : Observable<Response1> { var headers = new HttpHeaders(); headers.append('Content-Type', 'application/form-data'); const fd = new FormData(); fd.append('Type', 'Search'); fd.append('student_id', data.student_id.toString()); return this.http.post<Response1>("http://localhost:8080/StudentApi/",fd, {headers: headers } ); } }

In the Above File we have Created 5 Functions Which uses FORM DATA as Type and POST Method to fetch Data in observable in corresponding DataModel Which we have created Above . What Http.post does in angular it fetch data from server and converts it in JSON Object and assigned it to classes Object so that we can fully use our Object Oriented Programming Benefits

We have 5 APIs thats why we have created 5 Function to handle that API . In app.component.ts file we have handle all Click events and defines Function . Following Code describes it.

import { Component } from '@angular/core'; import { HttpcallService } from './httpcall.service'; import { Data } from './data'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Student Angular 5'; public items : Data[]; constructor(private httpcall:HttpcallService) { this.getAll(); this.data = new Data } getAll() { this.httpcall.getAllStudents().subscribe((data)=>{ this.items= data.data; }); } data:Data; public Name:string; public Address:string; public Telephone:string; public Standard:string; public RollNumber:string; public student_id:Number; Select(index :number) { this.data.student_id=this.items[index].student_id; this.httpcall.SearchStudents(this.data).subscribe((data)=>{ this.Name=data.data.Name; this.Address=data.data.Addres; this.Telephone= data.data.Telephone; this.Standard=data.data.Standard; this.RollNumber=data.data.Roll_Number; this.student_id =data.data.student_id; }); } Insert() { if(this.Name == undefined || this.Name == "" || this.Address == undefined || this.Address == "") { alert("Kindly Enter Name and Address"); }else { this.data.Name = this.Name; this.data.Addres=this.Address; this.data.Telephone=this.Telephone; this.data.Standard=this.Standard; this.data.Roll_Number=this.RollNumber; this.httpcall.InsertStudents(this.data).subscribe((data)=>{ alert(data.msg); this.getAll(); }) } } Update() { if(this.student_id == undefined ) { alert("Kindly Select one Record"); }else { this.data.Name = this.Name; this.data.Addres=this.Address; this.data.Telephone=this.Telephone; this.data.Standard=this.Standard; this.data.Roll_Number=this.RollNumber; this.data.student_id=Number(this.student_id); this.httpcall.UpdateStudents(this.data).subscribe((data)=>{ alert(data.msg); this.getAll(); }) } } Delete() { if(this.student_id == undefined ) { alert("Kindly Select one Record"); }else { this.data.student_id=Number(this.student_id); this.httpcall.DeleteStudents(this.data).subscribe((data)=>{ alert(data.msg); this.getAll(); }) } } }

Here We have Declared 3 functions Insert , Update , Delete to Perform Actions . In Insert We have passed Data Object with its Value in it to Web API . Which in response Provides . Operation status which we have Demanded .

One thing should be noted that we have assign Response1 datamodel in Search Function because it response is little different .

 

Full Project is at github . You can clone or download it and run it in your environment after setting up PHP Web APIs .

 

Project is here .

 

Output will be look like as below .

 

 





Leave a Comment


No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *