9951 explained code solutions for 126 technologies


angularjsHow do I use AngularJS to create a websocket example?


Using AngularJS to create a websocket example involves the following steps:

  1. Include the AngularJS library in your HTML page:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  1. Create an AngularJS module and inject the $websocket service:
var app = angular.module('myApp', ['ngWebSocket']);
  1. Create a service to establish a websocket connection with the server:
app.service('myService', function($websocket) {
  var dataStream = $websocket('ws://localhost:8080/');

  var collection = [];

  dataStream.onMessage(function(message) {
    collection.push(JSON.parse(message.data));
  });

  var methods = {
    collection: collection,
    get: function() {
      dataStream.send(JSON.stringify({ action: 'get' }));
    }
  };

  return methods;
});
  1. Inject the myService service into the controller:
app.controller('myCtrl', function($scope, myService) {
  $scope.collection = myService.collection;
});
  1. Use the myService.get() method to get data from the server:
myService.get();
  1. Bind the collection to the view to display the data:
<div ng-controller="myCtrl">
  <ul>
    <li ng-repeat="item in collection">{{item}}</li>
  </ul>
</div>
  1. Finally, open the websocket connection:
dataStream.onOpen(function() {
  console.log('connection is opened');
});

Output: connection is opened

Helpful links

Edit this code on GitHub