Saturday 20 May 2017

How to push websocket data to angularjs scope?

I am using autobahn and socket.io to successfully open a websocket connection and log the data in the serve console.

What I'm trying to do is to make that data available as a scope variable in my controller, so i can use the ng-repeater directive to display the data on the view.

//server.js

app.get('/open', function(req, res) {
  var autobahn = require('autobahn');
  var wsuri = "wss://api.poloniex.com";
  var connection = new autobahn.Connection({
    url: wsuri,
    realm: "realm1"
  });

  connection.onopen = function(session) {

    function tickerEvent(args, kwargs) {
      console.log(args); //logging live json data

      io.on('connection', function(socket) {
        socket.on('ticker', function(msg) {
          io.emit('ticker', msg); //I need 'msg' json to be in $scope.tickers
        });
      });
    }

    session.subscribe('ticker', tickerEvent);

  }

  connection.onclose = function() {
    console.log("Websocket connection closed");
  }

  connection.open();

})

Here I am trying to take the emitting message and push it to $scope.ticker so I can display it on index.html.

//websocket.js

app.controller('websocketController', function($scope, $http) {
  open_websocket();


  function open_websocket() {
    $http.get('http://localhost:3000/open').success(function(data) {
      io.on('connection', function(socket) {
        socket.on('ticker', function(msg) {
          $scope.tickers = msg; //trying to display this data on index.html
          console.log(msg); //not logging anything
        });
      });
    });
  };
});
<h1>index.html</h1>

<body>
  <div ng-app="websocket" ng-controller="websocketController">
    <ul ng-repeat="ticker in tickers">
      <li></li>
    </ul>
  </div>
</body>

How can I accomplish this?

Not looking for jQuery solution. Thanks.



via chuckieDub

No comments:

Post a Comment