How to refresh data from view without refreshing the whole page? angular -
i'am new angular 4 , i'm trying make website can show users logs. problem how can new data database , show angular page without refreshing page. friends told me use ajax, there built in solution in angular can solve problem? code on service
import { injectable } '@angular/core'; import {http,headers} '@angular/http'; import * _ 'underscore'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/topromise'; import {tokennotexpired} 'angular2-jwt'; @injectable() export class pagerservice { authtoken:any; constructor(private http:http) { } getzip(){ //gets data matches users zipcode var headers = new headers(); this.loadtoken();//access token headers.append('authorization',this.authtoken); headers.append('content-type','application/json'); return this.http.get('http://localhost:3000/logs/getbyname',{headers:headers}) .topromise().then((res) => res.json()); } loadtoken(){ var token = localstorage.getitem('id_token'); this.authtoken = token; //this.user = user; } getpager(totalitems: number, currentpage: number = 1, pagesize: number = 10) { // calculate total pages let totalpages = math.ceil(totalitems / pagesize); let startpage: number, endpage: number; if (totalpages <= 10) { // less 10 total pages show startpage = 1; endpage = totalpages; } else { // more 10 total pages calculate start , end pages if (currentpage <= 6) { startpage = 1; endpage = 10; } else if (currentpage + 4 >= totalpages) { startpage = totalpages - 9; endpage = totalpages; } else { startpage = currentpage - 5; endpage = currentpage + 4; } } // calculate start , end item indexes let startindex = (currentpage - 1) * pagesize; let endindex = math.min(startindex + pagesize - 1, totalitems - 1); // create array of pages ng-repeat in pager control let pages = _.range(startpage, endpage + 1); // return object pager properties required view return { totalitems: totalitems, currentpage: currentpage, pagesize: pagesize, totalpages: totalpages, startpage: startpage, endpage: endpage, startindex: startindex, endindex: endindex, pages: pages }; } }
and component.ts
import { component, oninit } '@angular/core'; import {pagerservice} '../../service/pager.service'; import {router} '@angular/router'; import { observable } 'rxjs/observable'; import { http, headers, requestoptions, response } '@angular/http'; import * _ 'underscore'; @component({ selector: 'app-messages', templateurl: './messages.component.html', styleurls: ['./messages.component.css'] }) export class messagescomponent implements oninit { constructor(private pagerservice:pagerservice, private router:router, private http:http ) { } doc:any[]; // array of items paged private allitems: any[]; // pager object pager: = {}; // paged items pageditems: any[]; row:any; ngoninit() { this.pagerservice.getzip().then(data =>{ this.allitems = data;this.setpage(1); console.log(json.stringify(this.allitems.length),"messages") },err=>{console.log(err); return false;}); } setpage(page: number) { if (page < 1 || page > this.pager.totalpages) { return; } // pager object service this.pager = this.pagerservice.getpager(this.allitems.length, page); // current page of items this.pageditems = this.allitems.slice(this.pager.startindex, this.pager.endindex + 1); console.log(this.pager.startindex,this.pager.endindex) } }
and if view:
<div *ngif="allitems && allitems.length <= 0" class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>well done!</strong> there no <a href="#" class="alert-link">messages display</a>. </div> <div *ngif="allitems && allitems.length > 0"> <table class="table table-striped table-hover "> <thead> <tr> <th></th> <th>plate number</th> <th>date</th> <th>time</th> <th>location</th> </tr> </thead> <tbody > <tr *ngfor ="let x of pageditems;let = index"> <td>{{i+(pager.startindex+1)}}</td> <td>{{x.platenumber}}</td> <td>{{x.date.month}}-{{x.date.dayn}}-{{x.date.year}}</td> <td>{{x.time}}</td> <td>{{x.location.street}}</td> </tr> </tbody> </table> </div> <div class = "text-center"> <!-- pager --> <ul *ngif="pager.pages && pager.pages.length" class="pagination"> <li [ngclass]="{disabled:pager.currentpage === 1}"> <a (click)="setpage(1)">first</a> </li> <li [ngclass]="{disabled:pager.currentpage === 1}"> <a (click)="setpage(pager.currentpage - 1)">previous</a> </li> <li *ngfor="let page of pager.pages" [ngclass]="{active:pager.currentpage === page}"> <a (click)="setpage(page)">{{page}}</a> </li> <li [ngclass]="{disabled:pager.currentpage === pager.totalpages}"> <a (click)="setpage(pager.currentpage + 1)">next</a> </li> <li [ngclass]="{disabled:pager.currentpage === pager.totalpages}"> <a (click)="setpage(pager.totalpages)">last</a> </li> </ul> </div>
in ideal case, there should push notification method setup server side tells client new data available.
if that's not available, can use setinterval()
update allitems
variable, hold data returned serice. suggest make these adjustments component.ts:
datarefresher: any; ngoninit() { this.getdata(true); this.refreshdata(); } getdata(setpageflag){ this.pagerservice.getzip().then(data =>{ this.allitems = data; if(setpageflag){ this.setpage(1); } console.log(json.stringify(this.allitems.length),"messages") }, err => { console.log(err); return false;}); } refreshdata(){ this.datarefresher = setinterval(() => { this.getdata(false); //passing false flag prevent page reset 1 , hinder user interaction }, 30000); }
refresh time set 30s, change whatever :)
you can add function clear interval , call on ngondestroy
:
cancelpagerefresh(){ if(this.datarefresher){ clearinterval(this.datarefresher); } } ngondestroy(){ this.cancelpagerefresh(); }
if using ondestroy
, don't forget import
, add in class implementation
Comments
Post a Comment