1

I've looked and haven't been able to find out how to handle a basic Comet proof-of-concept in AngularJS. I'm looking at Comet implemented by the client making repeated Ajax calls, rather than streaming JavaScript.

If I have a server-side CGI:

#!/bin/bash
echo "Content-type: application/json"
echo ""
echo "'"Hello world at "`/bin/date`"'!'"'"

What is a bare-bones AngularJS proof of concept that will query the server every second, and modulo network latency and the like, display a "Hello world!" that includes the server time?

Christos Hayward
  • 5,777
  • 17
  • 58
  • 113
  • Not sure what you mean by "modulo network latency and the like" are you just looking for an example of how to make an async call from Angular? – shaunhusain Mar 29 '14 at 00:34
  • A recurring async call, yes. On a real network, network latency and other conditions could mar an app's behavior as showing server time; I was basically trying to say, "Disregarding other nuances, how could an AngularJS Comet be written that would consume the CGI script's output and display the server time?" – Christos Hayward Mar 29 '14 at 16:06

1 Answers1

0

The Plunkr

http://plnkr.co/edit/6kpLplq5hy9e2sXMaEsG?p=preview

The HTML

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.15" src="http://code.angularjs.org/1.2.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp" ng-controller="MyCtrl">
    {{data.theDate}}
  </body>

</html>

The JS

angular.module("myApp", []).service("UpdatingService", function($http, $timeout){
  var service = {
    data:{},

    getData:function(){
      $http.get("someData.json").success(function(result){
        angular.copy(result, service.data)
        service.data.theDate+="    "+new Date();
      });
    }
  };

  cancelRefresh = $timeout(function myFunction() {
      service.getData();
      cancelRefresh = $timeout(myFunction, 1000);
  },1000);


  return service;
}).controller("MyCtrl", function($scope, UpdatingService){
  $scope.data = UpdatingService.data;
});

So I show how I would generally do this above. First create a service that handles doing the request and storing the data. Then make a controller and inject said service. Within the service inject the $http and $timeout services from angular so we can make the ajax request and can repeat the request thereby polling the server. Since there's no real setInterval the $timeout callback creates a new $timeout to continue the cycle, you can use the cancelRefresh if you need to stop the timer at some point details on that in the link below.

using setInterval in angularjs factory

Community
  • 1
  • 1
shaunhusain
  • 19,630
  • 4
  • 38
  • 51