0

I connect to a server through websockets with sockJS. When subscribe messages are retrieving, it does not update the $scope. I use a service to encapsulate websocket connection. Here is my service function .

    serviceMod.service('stompMessageService',function(){

        var mz = {msg:'initValue'};

    function connect() {

        var url='/hello/simplemessages';
        var socket = new SockJS(url);
        stompClient = Stomp.over(socket);

        stompClient.connect('user', 'guest', function(frame) {
            stompClient.subscribe("/topic/simplemessagesresponse", function(servermessage) {

                console.log('server msg: '+servermessage);
                mz.msg=servermessage;
            });
        });
    }
   connect();
    return mz;
    });

My controller

serviceMod.controller('stats', function($scope,stompMessageService) {

    $scope.mm=stompMessageService;

});  

in html page {{mm.msg}} . This gives only the first assign value 'initValue' not the server updates.(server response is comming. I tested with console.log().. ). .. Any one can let me know where can be problem

Débora
  • 5,816
  • 28
  • 99
  • 171
  • OMG, another one of $apply... just search a bit about $apply and the digest cycle. – coma Sep 14 '14 at 16:37
  • @coma, Thanks very much. I was searching.. but not found. finally I posted. if you put your guidance as an asnwer I ll accept it. – Débora Sep 14 '14 at 16:48
  • 1
    Ok, wait a bit, I didn't want to be rude, really, but 90% of the ng questions here are about $apply. – coma Sep 14 '14 at 16:51
  • 1
    The short answer is that you need to trigger $apply since the event is outside Angular's digest cycle, so the easy way to make it work is https://gist.github.com/coma/b21433d7fd69bb290ca2 , but I suggest you to study more about $apply, refreshing $rootScope is expensive so in my case (I'm using socket.io) I have a service that accept scopes as arguments and wrap them with the socket event listeners (and unbind them on scope.$destroy). But trust me, read about it. Here you have a wrapper: https://github.com/bendrucker/angular-sockjs – coma Sep 14 '14 at 17:19

0 Answers0