• Stars
    star
    1,222
  • Rank 38,138 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 11 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

↖️ The missing Angular WebSocket module for connecting client applications to servers by @AngularClass

Angular Websocket

Angular Websocket Join Slack Join the chat at https://gitter.im/AngularClass/angular-websocket gdi2290/angular-websocket API Documentation

Travis Bower npm Dependency Status devDependency Status NPM

Status: Looking for feedback about new API changes

An AngularJS 1.x WebSocket service for connecting client applications to servers.

How do I add this to my project?

You can download angular-websocket by:

  • (prefered) Using bower and running bower install angular-websocket --save
  • Using npm and running npm install angular-websocket --save
  • Downloading it manually by clicking here to download development unminified version
  • CDN for development https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.js
  • CDN for production https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.min.js

Usage

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="bower_components/angular-websocket/angular-websocket.js"></script>
  <section ng-controller="SomeController">
    <ul ng-repeat="data in MyData.collection track by $index" >
      <li> {{ data }} </li>
    </ul>
  </section>
  <script>
    angular.module('YOUR_APP', [
      'ngWebSocket' // you may also use 'angular-websocket' if you prefer
    ])
    //                          WebSocket works as well
    .factory('MyData', function($websocket) {
      // Open a WebSocket connection
      var dataStream = $websocket('ws://website.com/data');

      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;
    })
    .controller('SomeController', function ($scope, MyData) {
      $scope.MyData = MyData;
    });
  </script>

API

Factory: $websocket (in module ngWebSocket)

returns instance of $Websocket

Methods

name arguments description
$websocket
constructor
url:String Creates and opens a WebSocket instance.
var ws = $websocket('ws://foo');
send data:String,Object returns Adds data to a queue, and attempts to send if socket is ready. Accepts string or object, and will stringify objects before sending to socket.
onMessage callback:Function
options{filter:String,RegExp, autoApply:Boolean=true}
Register a callback to be fired on every message received from the websocket, or optionally just when the message's data property matches the filter provided in the options object. Each message handled will safely call $rootScope.$digest() unless autoApply is set to `false in the options. Callback gets called with a MessageEvent object.
onOpen callback:Function Function to be executed each time a socket connection is opened for this instance.
onClose callback:Function Function to be executed each time a socket connection is closed for this instance.
onError callback:Function Function to be executed each time a socket connection has an Error for this instance.
close force:Boolean:optional Close the underlying socket, as long as no data is still being sent from the client. Optionally force close, even if data is still being sent, by passing true as the force parameter. To check if data is being sent, read the value of socket.bufferedAmount.

Properties

name type description
socket window.WebSocket WebSocket instance.
sendQueue Array Queue of send calls to be made on socket when socket is able to receive data. List is populated by calls to the send method, but this array can be spliced if data needs to be manually removed before it's been sent to a socket. Data is removed from the array after it's been sent to the socket.
onOpenCallbacks Array List of callbacks to be executed when the socket is opened, initially or on re-connection after broken connection. Callbacks should be added to this list through the onOpen method.
onMessageCallbacks Array List of callbacks to be executed when a message is received from the socket. Callbacks should be added via the onMessage method.
onErrorCallbacks Array List of callbacks to be executed when an error is received from the socket. Callbacks should be added via the onError method.
onCloseCallbacks Array List of callbacks to be executed when the socket is closed. Callbacks should be added via the onClose method.
readyState Number:readonly Returns either the readyState value from the underlying WebSocket instance, or a proprietary value representing the internal state of the lib, e.g. if the lib is in a state of re-connecting.
initialTimeout Number The initial timeout, should be set at the outer limits of expected response time for the service. For example, if your service responds in 1ms on average but in 10ms for 99% of requests, then set to 10ms.
maxTimeout Number Should be as low as possible to keep your customers happy, but high enough that the system can definitely handle requests from all clients at that sustained rate.

CancelablePromise

This type is returned from the send() instance method of $websocket, inherits from $q.defer().promise.

Methods

name arguments description
cancel Alias to deferred.reject(), allows preventing an unsent message from being sent to socket for any arbitrary reason.
then resolve:Function, reject:Function Resolves when message has been passed to socket, presuming the socket has a readyState of 1. Rejects if the socket is hopelessly disconnected now or in the future (i.e. the library is no longer attempting to reconnect). All messages are immediately rejected when the library has determined that re-establishing a connection is unlikely.

Service: $websocketBackend (in module ngWebSocketMock)

Similar to httpBackend mock in AngularJS's ngMock module. You can use ngWebSocketMock to mock a websocket server in order to test your applications:

    var $websocketBackend;

    beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock');

    beforeEach(inject(function (_$websocketBackend_) {
      $websocketBackend = _$websocketBackend_;

      $websocketBackend.mock();
      $websocketBackend.expectConnect('ws://localhost:8080/api');
      $websocketBackend.expectSend({data: JSON.stringify({test: true})});
    }));

Methods

name arguments description
flush Executes all pending requests
expectConnect url:String Specify the url of an expected WebSocket connection
expectClose Expect "close" to be called on the WebSocket
expectSend msg:String Expectation of send to be called, with required message
verifyNoOutstandingExpectation Makes sure all expectations have been satisfied, should be called in afterEach
verifyNoOutstandingRequest Makes sure no requests are pending, should be called in afterEach

Frequently asked questions

  • Q.: What if the browser doesn't support WebSockets?
  • A.: This module will not help; it does not have a fallback story for browsers that do not support WebSockets. Please check your browser target support here and to include fallback support.

Development

$ npm install
$ bower install

Changelog

Changelog

Unit Tests

$ npm test Run karma in Chrome, Firefox, and Safari

Manual Tests

In the project root directory open index.html in the example folder or browserify example

Distribute

$ npm run dist Builds files with uglifyjs

Support, Questions, or Feedback

Contact us anytime for anything about this repo or Angular 2

TODO

  • Allow JSON if object is sent
  • Allow more control over $digest cycle per WebSocket instance
  • Add Angular interceptors
  • Add .on(event)
  • Include more examples of patterns for realtime Angular apps
  • Allow for optional configuration object in $websocket constructor
  • Add W3C Websocket support
  • Add socket.io support
  • Add SockJS support
  • Add Faye support
  • Add PubNub support

enjoy — AngularClass



AngularClass ##AngularClass

Learn AngularJS, Angular 2, and Modern Web Development form the best. Looking for corporate Angular training, want to host us, or Angular consulting? [email protected]

License

MIT

More Repositories

1

PatrickJS-starter

MFE Starter
JavaScript
10,330
star
2

awesome-angular

📄 A curated list of awesome Angular resources
HTML
9,463
star
3

NG6-starter

🆖 An AngularJS Starter repo for AngularJS + ES6 + Webpack
JavaScript
1,910
star
4

angular-hmr

🔥 Angular Hot Module Replacement for Hot Module Reloading
TypeScript
504
star
5

ngExam

An AngularJS exam with questions from beginner to expert by @gdi2290 from @AngularClass
363
star
6

Reddit-Insight

Reddit Analytics built in Angular.js
JavaScript
141
star
7

NG6-todomvc-starter

Basic example of TodoMVC application written with angular and with use of components
JavaScript
138
star
8

angular-md5

md5 for Angular.js and Gravatar filter
JavaScript
133
star
9

angular-idle-preload

🔜 Angular Idle Preload for preloading async routes via @TipeIO
TypeScript
99
star
10

angular-intercom

An Angular.js wrapper for Intercom.io providing a simple and familiar API for Angular Developer.
HTML
89
star
11

angular-raven

A Raven.js / Sentry wrapper for Angular.js
JavaScript
89
star
12

redis-dataloader

Batching and Caching layer using Redis as the Caching layer
JavaScript
86
star
13

node-everything

npm install everything. Please don't actually use this
82
star
14

awesome-cursorrules

📄 A curated list of awesome .cursorrules files
59
star
15

ng-vegas-angular2-d3

Angular 2, d3, and TypeScript
JavaScript
53
star
16

angular-momentjs

Moment.js with Angular
JavaScript
46
star
17

angular-password

The most performant AngularJS directive for matching two password input fields
JavaScript
45
star
18

data-structures

Data Structures in Javascript, Ruby, and Coffeescript
JavaScript
43
star
19

angular2do

TodoMVC: React setState/Immutable data pattern done in Angular2
HTML
39
star
20

koa-angular-seed

An Angular.js seed for Koa apps with gulp, stylus, and browserify
JavaScript
36
star
21

list-of-morphic-javascript

Javascript Morphisms
36
star
22

angular-crypto

angular-crypto provides standard and secure cryptographic algorithms for Angular.js with support for: MD5, SHA-1, SHA-256, RC4, Rabbit, AES, DES, PBKDF2, HMAC, OFB, CFB, CTR, CBC, Base64
JavaScript
31
star
23

everyone-ssn-usa

releasing everyone's SSN and the hacks used to acquire them
JavaScript
22
star
24

es6-promise-loader

JavaScript
21
star
25

ng-conf-2016-universal-patterns

ng-conf 2016 universal patterns
TypeScript
21
star
26

ng4-universal-demo

TypeScript
21
star
27

ruby_calculator

The simplest form of a calculator made in Ruby 2.0.0
Ruby
20
star
28

core-js-webpack-plugin

core-js builder as a Webpack Plugin
JavaScript
15
star
29

es7-reflect-metadata

Webpack and Universal support for reflect-metadata refactored by @gdi2290
HTML
13
star
30

hackreactor-presentation-slides

my HackReactor presentation
JavaScript
12
star
31

request-idle-callback

requestIdleCallback for Angular
TypeScript
10
star
32

angular-off

Providing the method $off for $rootScope in Angular.js
JavaScript
9
star
33

play-angular2

[WIP] Universal Angular 2 server rendering with Scala Play Framework
JavaScript
9
star
34

angular2-webpack2-seed

angular2 webpack2 with tree-shaking and precompiler??
TypeScript
9
star
35

awesome-JAMstack

A collection of awesome JAMstack starters, workflows, articles, resources and shiny things.
9
star
36

angular-example-basic-form

An AngularJS example for a basic signup form example
JavaScript
9
star
37

angular-d3

d3 for Angular.js
JavaScript
8
star
38

angular-event-emitter

Event emitters for AngularJS
JavaScript
8
star
39

angular-keen.io

An Angular.js wrapper for Keen.io
JavaScript
8
star
40

angular-pokemon

Pokemon directive for Angular.js
JavaScript
8
star
41

generator-easy

An EASY stack generator, Express Angular Stylus Yeoman
CSS
7
star
42

angular-beforeunload

Angular.js service for onBeforeUnload
JavaScript
7
star
43

dokku-bower-gulp-build-plugin

dokku-bower-gulp-build is a plugin for dokku that runs bower install and gulp build in a post-release hook.
7
star
44

angular-cors

Fast CORs support for angular1
JavaScript
6
star
45

ngSanitize

angular-sanitize module without including angular.js for Backbone and other frameworks
JavaScript
6
star
46

angular2-falcor-starter

Angular 2 Universal FalcorJS starter kit by @AngularClass
TypeScript
6
star
47

bower-everything

bower install everything
JavaScript
6
star
48

simple-universal-starter

TypeScript
5
star
49

read-this-Howard

Status: offline!
5
star
50

angular-groupon

An Angular.js wrapper for Groupon API
JavaScript
5
star
51

no-zone.js

No Zone.js allows you to use zone.js API without actually using it. (recommended for advanced use cases only)
JavaScript
5
star
52

angular-uuid-secure

Most secure uuid generator in for Angular.js
JavaScript
4
star
53

angular-balanced

An Angular.js adapter for Balanced.js
4
star
54

angular2-webpack

Webpack helpers for Angular 2 via @AngularClass
JavaScript
4
star
55

ng-click

Passive URL shortening for Angular.JS Docs
JavaScript
4
star
56

angular-facebook

An Angular.js wrapper for Facebook API
4
star
57

github-commit-messages

This chrome extension will show and hide scoped messages so its easier to read quickly
JavaScript
4
star
58

traceur-compiler-loader

Up to date Traceur Compiler loader for Webpack
JavaScript
4
star
59

ngx-loader

ngx-loader
JavaScript
4
star
60

angular2-amp

angular2-amp: nothing to see here
4
star
61

javascript-class-examples

Different examples of OOP "class" with "inheritance" done using JavaScript including languages that transpile into js. Take notice to the amount of boilerplate that's needed in ES5 compared to ES6. These examples all have the same interface with pros/cons for each pattern. If they seem similar that's whole point especially the difference between prototypal and pseudo-classical.
JavaScript
4
star
62

Data-Collaborator

Data visualizations unlock insights and initiate important conversations Our tool, Data Collaborator, enables people to create data visualizations about their Fitbit data, and collaborate with their friends and family, doctors and personal trainers about insights they have about these visualizations
JavaScript
4
star
63

promises

Promises/A+ implementation base on http://promises-aplus.github.io/promises-spec/
JavaScript
3
star
64

git-mv

Keep the git history of your git mv files after undo
Shell
3
star
65

angular-pubnub

A PubNub component for Angular.js
JavaScript
3
star
66

angular-webrtc

3
star
67

angular-algolia

wip
3
star
68

es7-tools

An aggregation of tooling for using ES7 today
3
star
69

angular-async

Async unwrap filters for Angular1 from Angular2 AsyncPipe
HTML
3
star
70

universal-lit-html

Universal Rendering support for lit-html by Polymer
JavaScript
3
star
71

ng2dist

AsyncPipe build of angular 2
JavaScript
3
star
72

angular2-server-rendering

(Initial prototype) Angular 2 Server Rendering
JavaScript
3
star
73

FrontendMasters-2015-02-13-React

React.js Workshop with Ryan Florence
JavaScript
3
star
74

HackerTweet

JavaScript Twitter clone project for HackReactor pre-work made in Rails 4.0.0.beta1 and jQuery
JavaScript
3
star
75

ie-shim

ie-shim for Angular 2
JavaScript
3
star
76

angular-flux

Flux Application Architecture for Angular.js allow AngularJS apps to have unidirectional data flow in a single direction, in a cycle
3
star
77

made-at-hackreactor

Made at HackReactor built in Rails 3.2.13, Backbone.js 1.0.0, Redis 2.6.13, Socket.io 0.9, Node.js 0.10.12
JavaScript
3
star
78

angular-free-style

An Angular.js module for free-style that is designed to make cross-browser style objects easier to work with in JavaScript
JavaScript
3
star
79

angular2-example-falcor

Angular2 + FalcorJS
JavaScript
3
star
80

systemjs-d3

SystemJS wrapper for d3.js
2
star
81

preload_cache.js

PreloadCache: preload_cache defers cache until after the app bootstraps by providing deferred refs. NOTE: In process of moving this repo to angular/universal
HTML
2
star
82

test-static-file

testing static files
HTML
2
star
83

angular2-example-iot

Angular 2 example for Internet of Things
JavaScript
2
star
84

angular-bluebird

An Angular.js wrapper around Bluebird's API as $promise
2
star
85

angular2-universal-cluster

node cluster for Angular 2 Universal
TypeScript
2
star
86

node-hammerjs

Node "support" for hammerjs
JavaScript
2
star
87

gulp-loopback-angular

Gulp plugin for auto-generating Angular $resource services for LoopBack
2
star
88

gdi2290.github.io

HTML
2
star
89

lower-case

Lowercase a string in JavaScript
JavaScript
2
star
90

test-repo_login-to-see-resolved-comment

testing public resolved comments
2
star
91

underbar

this is for learning javascript
JavaScript
2
star
92

angular-reddit

Reddit API for Angular.js
2
star
93

angular-olark

An Angular.js service for Olark a live chat service
2
star
94

PatrickJS

2
star
95

awesome-rx

Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators.
2
star
96

angular-alertify

JavaScript
2
star
97

is-iojs-production-ready-yet

is io.js production ready yet?
2
star
98

snake-case

Snake case a string in JavaScript
JavaScript
2
star
99

angular2-beta-to-rc-alias

Alias Angular 2 beta.17 3rd party modules to Angular 2 rc.3 modules
TypeScript
2
star
100

ng2for1

angular1 hacks for angular2 style coding
JavaScript
2
star