简体   繁体   中英

How to bind an http service to a variable in angularjs when server data changes?

I use an http get request in angular for extract data in a object with the users connected at the moment in my app. But that info need to be refreshed every time for bind to the scope. So I made this for refresh every 3 seconds the data of the array in get request ->

index.jade

a(ng-repeat="item in room.connected")
img(src="/images/{{item.avatar}}")

controller.js

ngApp.controller('controller', function(){

   var vm = this;  vm.connected;

   $interval(function(){
   //The Get request returns an array like->[{"username":"cesarodriguez4","avatar":"icon-user-man-1.png"}]
   $http.get('http://localhost:3000/get-classroom-viewers/user')
   .then(function(response){
         vm.connected = response.data;
         },function(error){
         console.log(error);
        });
     }, 3000);
   //Every 3 seconds executes the GET request.
   });

That works, but i think its not the correct, because the terminal shows every time the get request and I think that's a bad practice Does an method for refresh the info only when the server changes the data? I try Using $scope.$watch but does not work.

You should use websockets, so that if anything changes in the server side you can push to sockets, from socket you can read and update the scope variable. Looping or making server request on every 3 sec is bad practice as it increases server load.

SockJS Angular Client

angular.module('myApp')
.service('PushNotificationService', ['$q', '$timeout', function($q, $timeout) {

   var service = {}, listener = $q.defer(), socket = {
      client: null,
      stomp: null
    };

    service.RECONNECT_TIMEOUT = 30000;
    service.SOCKET_URL = 'your socket Url'; // like '/chat'
    service.CHAT_TOPIC = 'topic url'; // like '/getMessage/chat'  

    service.receive = function() {
      return listener.promise;
    };

    var reconnect = function() {
      $timeout(function() {
        initialize();
      }, this.RECONNECT_TIMEOUT);
    };


    var startListener = function() {
      socket.stomp.subscribe(service.CHAT_TOPIC, function(data) {                 
          var jsonObj = JSON.parse(data.body);
        listener.notify(jsonObj);
      });
    };

    var initialize = function() {
      socket.client = new SockJS(service.SOCKET_URL);
      socket.stomp = Stomp.over(socket.client);
      socket.stomp.connect({}, startListener);
      socket.stomp.onclose = reconnect;
    };

    initialize();
    return service;
}]);

In your controller

angular.module('myApp').controller('myCtrl', function($scope, PushNotificationService) {
     PushNotificationService.receive().then(null, null, function(message) {

                   //message contains data you pushed to socket from server

            //assign data to $scope variable
          $scope.data = message;
                });
})

Include below scripts in your html

sockjs.js
stomp.js

More Info

Websocket using Spring AngularJS SockJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM