In this tutorial, I will show you how to pull the data from back-end periodically to keep your UI up to date. In this tutorial, I will mainly focus on Observable, which is imported from rxjs/Rx. In this tutorial, I will use to-do Application, which is created previously to display the new task, add the new task, update the task and delete the task. You can find more about it here. In this tutorial, I am using the same project, which is available in GitHub.
First, start with creating addtask.component
Addtasks.component.html
- [code language=”html”]
- <div class="container">
- <div class="row">
- <form (ngSubmit)="taskSubmit()" #addform="ngForm">
- <div class="form-group">
- <label for="id">Id</label>
- <input type="number" [(ngModel)]="model.Id"
- name="id"
- class="form-control" id="id"
- required #id="ngModel">
- </div>
- <div [hidden]="id.valid || id.pristine"
- class="alert alert-danger">
- Task Id is required
- </div>
-
- <div class="form-group">
- <label for="name">Task</label>
- <input type="text" [(ngModel)]="model.Title"
- name="title"
- class="form-control" id="name"
- required #title="ngModel">
- </div>
- <div [hidden]="title.valid || title.pristine"
- class="alert alert-danger">
- Task Title is required
- </div>
- <div class="form-group">
- <label for="power">Status</label>
- <select class="form-control" id="status"
- [(ngModel)]="model.Status" name="status"
- required>
- <option *ngFor="let s of status" [value]="s">{{s}}</option>
- </select>
- </div>
- <button type="submit" class="btn btn-primary form-control" [disabled]="!addform.form.valid" >Add Task</button>
- </form>
- </div>
- </div>
- [/code]
Addtasks.component.ts
- [code language=”typescript”]
- import { Component, OnInit } from '@angular/core';
- import { Task } from './task';
- import { TaskdataService } from '../taskdata.service';
- import { Router } from '@angular/router';
- @Component({
- selector: 'app-addtask',
- templateUrl: './addtask.component.html',
- styleUrls: ['./addtask.component.css']
- })
- export class AddtaskComponent implements OnInit {
- status = ['pending','done'];
- model = {Id:'',Title:'',Status:'pending'};
- constructor(private _data:TaskdataService,private _router:Router) { }
-
- ngOnInit() {
- }
- taskSubmit(){
-
- this._data.addTask(this.model).subscribe(
- (data:any)=>{
- this._router.navigate(['/allTask']);
- }
- );
- }
- }
- [/code]
In the code given above, I used a template driven approach and using two way data binding, added a new task to the database. For more about add, update and delete task; use the the link given above.( https://jinalshahblog.wordpress.com/2016/12/28/crud-in-angular2-part2/)
Tasks.component.html
- [code language=”html”]
- <div class="row">
- <table class="table">
- <thead>
- <th>Id</th>
- <th>Title</th>
- <th>Status</th>
- <th>Action</th>
- </thead>
- <tbody>
- <tr *ngFor="let item of allTask ">
- <td>{{item.Id}}</td>
- <td>{{item.Title | uppercase}}</td>
- <td><span [ngClass]="{'pendingstatus': item.Status=='pending','donestatus':item.Status=='done'}" >{{item.Status}}</span></td>
- <td><button (click)="delTask(item)"><span class="glyphicon glyphicon-trash"></span></button>
-
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- [/code]
Tasks.component.ts
- [code language=”typescript”]
- import { Component, OnInit , OnDestroy } from '@angular/core';
- import { Task } from './task';
- import { TaskdataService } from '../taskdata.service';
- import { Observable } from 'rxjs/Rx';
- import {AnonymousSubscription} from "rxjs/Subscription";
- @Component({
- selector: 'app-tasks',
- templateUrl: './tasks.component.html',
- styleUrls: ['./tasks.component.css']
- })
- export class TasksComponent implements OnInit {
- allTask:Task[]=[];
- private timerSubscription: AnonymousSubscription;
- private postsSubscription: AnonymousSubscription;
- constructor(private _data:TaskdataService) { }
-
- ngOnInit() {
- this.refreshData();
- }
- delTask(item:Task){
- event.stopPropagation();
- this._data.deleteTask(item).subscribe(
- (data:any)=>{
- this.allTask.splice(this.allTask.indexOf(item),1);
- },
- function(error){
- }
- );
- }
- public ngOnDestroy(): void {
- if (this.postsSubscription) {
- this.postsSubscription.unsubscribe();
- }
- if (this.timerSubscription) {
- this.timerSubscription.unsubscribe();
- }
- }
- private subscribeToData(): void {
-
- this.timerSubscription=Observable.timer(5000)
- .subscribe(()=>this.refreshData());
- }
- private refreshData():void{
- this.postsSubscription= this._data.getAllTask().subscribe(
- (data:Task[])=>{
- this.allTask=data;
- this.subscribeToData();
- },
- function(error){
- console.log(error);
- },
- function(){
- console.log("complete");
- }
- );
- }
- }
- [/code]
Here, in the code given above, I created one method named as refreshdata, which will call the Service getAllTask which will fetch allTask from the database and on success of this method, I had given response/data to allTask array. Afterwards also call another method subscribeToData,which sets the timer of 5 seconds and then again call refreshdata. In this way, we can pull the data from the database.
Also, don’t forget to unsubscribe from subscribeToData on ngOnDestroy to prevent the memory leakage issue.
Output
- Two screens are there, where one displays record and one is for adding a new task.
- First screen has still not received an update, while second screen added the record and navigated back to all the task, so it gets the updates.
- Finally, both screens get the record.(timer called after 5 seconds).
In this tutorial, I covered how to fetch the data periodically from the database to keep UI updated.
Find the source code here and feel free to play with the code yourself.
I hope, it will be helpful to you. Thanks for reading.