AngularJS Polling Spring MVC example
In this example you will see how to use polling in AngularJS. AngularJS provide service $timeout which is wrapper for “window.setTimeout”. When calling $timeout service it return value is promise. If you want to cancel timeout request then call $timeout.cancel(promise)
Usage:
$timeout([fn], [delay], [invokeApply]);
- Sample maven project final screen shot:
- index.jsp:
<!DOCTYPE html> <html data-ng-app="myApp"> <head lang="en"> <meta charset="utf-8"> <title>AngularJS server polling example</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('MyController', function($scope, $http, $timeout) { $scope.value = 1; var polling = function() { var value = $http({ method : 'GET', url : 'pollDataFromServer' }); value.success(function(data, status, headers, config) { $scope.randomNumber = data; }); $timeout(function() { $scope.value++; polling(); }, 1000); }; //Call function polling() polling(); }); </script> </head> <body data-ng-controller="MyController"> <h3>AngularJS server polling example</h3> <div> <p>Random Number from server on every call: {{randomNumber}} </p> <p>Call made to the server: {{value}} Times</p> </div> </body> </html>
- AngularJSPollController.java – When call comes to the server return random integer value just to show up call goes to the server and data is getting refreshed:
package com.javahonk.controller; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class AngularJSPollController { @RequestMapping(value = "/pollDataFromServer") public @ResponseBody List<Integer> populateActivePSwapBasket() { Random rand = new Random(); Integer randomNum = rand.nextInt(); List<Integer> list = new ArrayList<Integer>(); list.add(randomNum); return list; } }
- Output:
- For more information on $timeout please visit AngularJS API here
Download project: AngularJSPolling
It is nice..