Sunteți pe pagina 1din 18

Jinal Shah

Let's Do it…

CRUD operations in Ionic2 , To-Do application

Posted on January 18, 2017 by Jinal Shah


Hello Readers,

Now It is time for Ionic2(Cross Platform Mobile App Using AngularJS and Typescript). If you know
angularJS and Typescript then it is your “cup of tea”.

In this tutorial I am going to cover following topics.

HTTP Services(Providers)
Fetching JSON Data From URL
Add task
Conditionally applying css class
Delete Task
Update Task & more..

You can also find the code here (h ps://github.com/jinalshah999/ionic2todoapplication.git), So feel free
to play with code yourself. In this tutorial I am using Ionic2 CLI (Command Line Interface to have work
convenience with ionic2). In other word by using cli it will create boiler plate ready for us. For setup and
all other instructions please go through the previous article here..
(h ps://jinalshahblog.wordpress.com/2016/11/19/ge ing-started-with-ionic-2-cli/)

In this tutorial I am going to make to-do application to simply list all task, add task, delete task and
update task. I had already created the REST Api Using NodeJS.
(h ps://jinalshahblog.wordpress.com/2016/10/06/rest-api-using-node-js-and-mysql/),so it will fetch data
from mysql. My Task Table Contains 3 columns Id, Title & Status.

Creating Data Structure/Class:

1 export class Task {


2
3 constructor(public Id:String,public Title:String,public Status:String){}
4
5 }

First I had created class and named it as Task, it will be used to store the json data.
j

What are services?

We can say, services mean don’t repeat yourself (Dry)!

Now, what does it mean?

Let’s say for example, we require one function which can be used by more than one components. Then,
what happens, we just need to write the same code again and again for each component. When we want
to change some logic in function, then we need to change it on each and every component.

i.e. instead of doing this, we simply create a service in which we can write the code once that can be
used by as many components as we want ,by simply injecting the service Instance. In other languages,
services keeps our function and logic centralized.

In general, our service can perform the following tasks:

Communicate with database.


Communicate with components /classes.
Some other business logic which is accessible from various places of our application.

Creating Provider/Service:

cmd> ionic g provider dbtaskservice

1 public url:string="https://localhost:3000/Tasks/ (https://localhost:3000/Tasks/


2
3 getAllTasks(){
4
5 return this._http.get(this.url)
6
7 .map((response:Response)=>response.json());
8
9 }

The above function will return all the task from the database. But before creating this function ,create the
object of HTTP as shown below and also import rxjs/Rx for map and observable.

1 import { Injectable } from '@angular/core';


2
3 import { Task } from '../pages/tasks/task';
4
5 import { Http,Response,RequestOptions,Headers } from '@angular/http';
6
7 import { Observable } from "rxjs/Observable";
8
9 import 'rxjs/Rx';
10
11 @Injectable()
12
13 export class Dbtaskservice {
14
15 private allTask:Task[]=[];
16
17 private url:string="https://localhost:3000/Tasks/ (https://localhost:3000/Task
18
19 constructor(public _http: Http)
20
21 {
22
23 console.log('Hello Dbtaskservice Provider');
24
25 }
26
27 getAllTask()
28
29 {
30
31 return this._http.get(this.url)
32
33 .map((response:Response)=>response.json());
34
35 }
36
37 deleteTask(item:Task){
38
39 let headers = new Headers({ 'Content-Type': 'application/json' });
40
41 let options = new RequestOptions({ headers: headers });
42
43 return this._http.delete(this.url+item.Id,
44
45 options)
46
47 .map((response:Response)=>response.json());
48
49 }
50
51 addTask(item:Task){
52
53 let body = JSON.stringify(item);
54
55 let headers = new Headers({ 'Content-Type': 'application/json' });
56
57 let options = new RequestOptions({ headers: headers });
58
59 return this._http.post(this.url,
60
61 body, options)
62
63 .map((response:Response)=>response.json());
64
65 }
66
67 getTaskId(id:any){
68
69 return this._http.get(this.url+id)
70
71 .map((response:Response)=>response.json());
72
73 }
74
75 editTask(item:Task){
76
77 let body = JSON.stringify(item);
78
79 let headers = new Headers({ 'Content-Type': 'application/json' });
80
81 let options = new RequestOptions({ headers: headers });
82
83 return this._http.put(this.url+item.Id,
84
85 body, options)
86
87 .map((response:Response)=>response.json());
88
89 }
90
91 }

So here in above service I had created all methods for task like getAllTask(),addTask(),deleteTask() and
more.

Important Point:

To make this service available to each component, it must be declared inside the provider array of
app.module.ts (i.e. global declaration file) as shown below.
1 import { NgModule } from '@angular/core';
2
3 import { IonicApp, IonicModule } from 'ionic-angular';
4
5 import { MyApp } from './app.component';
6
7 import { AboutPage } from '../pages/about/about';
8
9 import { ContactPage } from '../pages/contact/contact';
10
11 import { Dbtaskservice } from '../providers/dbtaskservice';
12
13 @NgModule({
14
15 declarations: [
16
17 MyApp,
18
19 AboutPage,
20
21 ContactPage
22
23 ],
24
25 providers: [Dbtaskservice]
26
27 })

Creating Component:

So far I had created class and service, now it’s turn for component to display all the task.

cmd>ionic g page tasks

it will generate tasks directory inside pages directory.

Ionic2 comes with global declaration concept. So, whenever creating a component, it must need to
declare it in app.module.ts, inside the declaration array and entryComponents array as shown below,
then only it can be used.
1 import { NgModule } from '@angular/core';
2
3 import { IonicApp, IonicModule } from 'ionic-angular';
4
5 import { MyApp } from './app.component';
6
7 import { AboutPage } from '../pages/about/about';
8
9 import { ContactPage } from '../pages/contact/contact';
10
11 import { TasksPage } from '../pages/tasks/tasks';
12
13 @NgModule({
14
15 declarations: [
16
17 MyApp,
18
19 AboutPage,
20
21 ContactPage,
22
23 TasksPage
24
25 ],
26
27 entryComponents: [
28
29 MyApp,
30
31 AboutPage,
32
33 ContactPage,
34
35 HomePage,
36
37 TasksPage
38
39 ],
40
41 })

Component can be divide in to two part

1. Html
2. TypeScript

I will first start with TypeScript part. Now TypeScript can be further divide in 3 parts.

1. Import section
2. Component metadata
3. Class

So, in our example –

First, create the array named it as allTasks which is the type of task(which is created earlier).
Then, inject the dbtaskservice inside the constructor and create the instance of our service.
And then finally, call getAllTask method of our service inside the ionViewDidLoad event.

1 import { Component } from '@angular/core';


2
3 import { NavController ,LoadingController ,ToastController } from 'ionic-angul
4
5 import { Dbtaskservice } from '../../providers/dbtaskservice';
6
7 import { Task } from '. /task';
8
9 @Component({
10
11 selector: 'page-tasks',
12
13 templateUrl: 'tasks.html'
14
15 })
16
17 export class Tasks {
18
19 allTask:Task[]=[];
20
21 title:string;
22
23 id:string;
24
25 constructor(public navCtrl: NavController,public loadincontroller:LoadingContr
26
27 }
28
29 ionViewDidLoad() {
30
31 let loadingdata=this.loadincontroller.create({
32
33 content:"Loading Tasks..."
34
35 });
36
37 loadingdata.present();
38
39 this._dbtaskservice.getAllTask().subscribe(
40
41 (data:Task[])=>{
42
43 this.allTask=data;
44
45 },
46
47 function (error){
48
49 console.log("error"+error)
50
51 },
52
53 function(){
54
55 loadingdata.dismiss();
56
57 }
58
59 );
60
61 }
62
63 }

In Above code, I had imported loadingcontroller from ionic-angular package, to show progress bar on
loading also imported toastcontroller to display the message on successfully insert or delete or update
the task. Now on html I will loop through the allTask array and display all the task. So the html will look
like following.

1 <ion-header>
2
3 <ion-navbar>
4
5 <ion-title>taskdb</ion-title>
6
7 </ion-navbar>
8
9 </ion-header>
10
11 <ion-content padding>
12
13 <ion-list inset>
14
15 <ion-input placeholder="id" autofocus="" [(ngModel)]="id" ></ion-input>
16
17 <ion-input placeholder="What needs to be done?" [(ngModel)]="title" (keyup.en
18
19 <ion-item *ngFor="let t of allTask" ><!--(click)="taskSelected(t)"-->
20
21 <ion-label [ngClass]="{'donestatus': t.Status=='done','pendingstatus':t.Status
22
23 <ion-icon item-right (click)="deleteTask(t)" ios="ios-trash" md="md-trash"></
24
25 <ion-icon item-right (click)="updateTask(t)" ios="ios-color-wand" md="md-colo
26
27 <!--<ion-icon name="trash" ios="ios-trash" md="md-trash"></ion-icon>-->
28
29 </ion-item>
30
31 </ion-list>
32
33 </ion-content>

Here in above html I am also applying the class conditionally i.e. the completed task should be displayed
in blue and uncompleted task should be displayed in red.
1 page-tasks {
2
3 .donestatus{
4
5 color: blue;
6
7 }
8
9 .pendingstatus{
10
11 color: red;
12
13 }
14
15 }

Also I had used two way binding for adding the task.

1 <ion-input placeholder="id" autofocus="" [(ngModel)]="id" ></ion-input>


2
3 <ion-input placeholder="What needs to be done?" [(ngModel)]="title" (keyup.ent

Two way binding can be achieved using ngModel. Here I created the keyup event which fired on enter
key pressed. Overall typescript will look like this after adding addTask,updateTask and deleteTask.

1 import { Component } from '@angular/core';


2
3 import { NavController ,LoadingController ,ToastController } from 'ionic-angu
4
5 import { Dbtaskservice } from '../../providers/dbtaskservice';
6
7 import { Task } from './task';
8
9 @Component({
10
11 selector: 'page-tasks',
12
13 templateUrl: 'tasks.html'
14
15 })
16
17 export class Tasks {
18
19 allTask:Task[]=[];
20
21 title:string;
22
23 id:string;
24
25 constructor(public navCtrl: NavController,public loadincontroller:LoadingCont
26
27 ,public _toast:ToastController){
28
29 &nbsp;
30
31 }
32
33 &nbsp;
34
35 ionViewDidLoad() {
36
37 console.log('Hello Taskdb Page');
38
39 let loadingdata=this.loadincontroller.create({
40
41 content:"Loading Tasks..."
42
43 });
44
45 loadingdata.present();
46
47 this._dbtaskservice.getAllTask().subscribe(
48
49 (data:Task[])=>{
50
51 this.allTask=data;
52
53 console.log(data);
54
55 },
56
57 function (error){
58
59 console.log("error"+error)
60
61 },
62
63 function(){
64
65 console.log("subscription done")
66
67 loadingdata.dismiss();
68
69 }
70
71 );
72
73 }
74
75 addTask(){
76
77 let loadingdata=this.loadincontroller.create({
78
79 content:"Posting Tasks..."
80
81 });
82
83 loadingdata.present();
84
85 this._dbtaskservice.addTask(new Task(this.id,this.title,'pending'))
86
87 .subscribe(
88
89 (data:Task)=>{
90
91 if(data!=null){
92
93 this.allTask.push(new Task(this.id,this.title,'pending'));
94
95 this.title='';
96
97 this.id='';
98
99 }
100
101 },
102
103 function(error){},
104
105 function(){
106
107 loadingdata.dismiss();
108
109 }
110
111 &nbsp;
112
113 );
114
115 }
116
117 updateTask(t:Task){
118
119 if(t.Status=='done')
120
121 {
122
123 t.Status='pending';
124
125 }
126
127 else
128
129 {
130
131 t.Status='done'
132
133 }
134
135 this._dbtaskservice.editTask(t).subscribe(
136
137 (data:any)=>{
138
139 &nbsp;
140
141 if(data.affectedRows==1)
142
143 {
144
145 let mes=this._toast.create({
146
147 message:'Task Updated Successfully',
148
149 duration:2000,
150
151 position:'bottom'
152
153 });
154
155 &nbsp;
156
157 mes.present();
158
159 }
160
161 else
162
163 {
164
165 let mes=this._toast.create({
166
167 message:'Error in Updating',
168
169 duration:2000,
170
171 position:'bottom'
172
173 });
174
175 &nbsp;
176
177 mes.present();
178
179 }
180
181 }
182
183 );
184
185 }
186
187 deleteTask(t:Task){
188
189 &nbsp;
190
191 this._dbtaskservice.deleteTask(t).subscribe(
192
193 (data:any)=>{
194
195 &nbsp;
196
197 if(data.affectedRows==1){
198
199 &nbsp;
200
201 let mes=this._toast.create({
202
203 message:'Task Deleted Successfully',
204
205 duration:2000,
206
207 position:'bottom'
208
209 });
210
211 this.allTask.splice(this.allTask.indexOf(t),1);
212
213 mes.present();
214
215 }
216
217 else{
218
219 let mes=this._toast.create({
220
221 message:'Error in deleting task',
222
223 duration:2000,
224
225 position:'bottom'
226
227 });
228
229 mes.present();
230
231 }
232
233 }
234
235 );
236
237 }
238
239 }

I had created the tab application so before running the application I must need to change the default
page i.e. go to tab page and change the home page to tasks page as shown below
1 import { Component } from '@angular/core';
2
3 import { HomePage } from '../home/home';
4
5 import { AboutPage } from '../about/about';
6
7 import { ContactPage } from '../contact/contact';
8
9 import { Tasks } from '../tasks/tasks';
10
11 @Component({
12
13 templateUrl: 'tabs.html'
14
15 })
16
17 export class TabsPage {
18
19 // this tells the tabs component which Pages
20
21 // should be each tab's root Page
22
23 tab1Root: any = Tasks;
24
25 tab2Root: any = AboutPage;
26
27 tab3Root: any = ContactPage;
28
29 constructor() {
30
31 &nbsp;
32
33 }
34
35 }

So now all done and good to go to run to-do application.

Run application in browser

cmd>ionic serve

Run application in device

cmd>ionic run android

but before run on device I must need to add platform for it

cmd>ionic platform add android


(h ps://jinalshahblog.wordpress.com/2017/01/18/crud-operations-in-ionic2-

to-do-application/screenshot-114/)

(h ps://jinalshahblog.wordpress.com/2017/01/18/crud-operations-in-ionic2-

to-do-application/screenshot-115/)

(h ps://jinalshahblog.wordpress.com/2017/01/18/crud-operations-in-ionic2-to-

do-application/screenshot-116/)
(h ps://jinalshahblog.wordpress.com/2017/01/18/crud-operations-in-ionic2-to-

do-application/screenshot-117/)

(h ps://jinalshahblog.wordpress.com/2017/01/18/crud-operations-in-ionic2-to-do-application/screenshot-
118/)

Summary
Ionic2 is simply awesome. Isn’t it?

Download link (h ps://github.com/jinalshah999/ionic2todoapplication.git)

We covered a lot in this tutorial. Let’s just summarize it.

Ionic-CLI
Created class
Services
Components
Run time css class
Add,Update and Delete and more…

There is a lot more to come in the next part of the tutorial. So, stay tuned for more.

Advertisements

Posted in Angular2, ionic 2


Published by Jinal Shah

i am freelance trainer on different technology like node.Js, Angular2, BOT Framework etc. i had done my
B.E. (Computer) from C.U. Shah College of Engg. & Tech., Wadhwan City, Surendranagar in year 2009. i
am running own coaching classes in Ahmedabad, Gujarat for different I.T. subjects & also co-founder in
Brainoorja Creations. h p://brainoorja.com i am actively associated with academics and trainings to I.T.
students of various colleages studying in B.E., B.Sc. (IT), B.C.A./M.C.A. my latest blogs and workshop
details are published at: h ps://jinalshahblog.wordpress.com my core expertise lies in imparting
trainings on Angular2 and hands-on experience on other web technologies like, ASP.NET, MVC , C#
NET, Android. my hobbies are research, development and trainings in upcoming web & mobile
technologies. i can be reached at: +91 98258 89888 and jinalshah999@gmail.com View all posts by Jinal Shah

2 thoughts on “CRUD operations in Ionic2 , To-


Do application”

1. Mritunjay Singh February 10, 2017 Reply

hello sir please tell how to use restful php api with mysql in ionic 2

2. TÜRKALP KUCUR August 1, 2017 Reply

perfect! I am waiting for more ionic2, angular2 examples! thanks!

Create a free website or blog at WordPress.com.

S-ar putea să vă placă și