Giter VIP home page Giter VIP logo

angular-socket-io's Introduction

angular-socket-io Build Status

Bower Component for using AngularJS with Socket.IO, based on this.

Install

  1. bower install angular-socket-io or download the zip.
  2. Make sure the Socket.IO client lib is loaded. It's often served at /socket.io/socket.io.js.
  3. Include the socket.js script provided by this component into your app.
  4. Add btford.socket-io as a module dependency to your app.

Usage

This module exposes a socketFactory, which is an API for instantiating sockets that are integrated with Angular's digest cycle.

Making a Socket Instance

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  return socketFactory();
});

With that, you can inject your mySocket service into controllers and other serivices within your application!

Using Your Socket Instance

Building on the example above:

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  return socketFactory();
}).
controller('MyCtrl', function (mySocket) {
  // ...
});

API

For the most part, this component works exactly like you would expect. The only API addition is socket.forward, which makes it easier to add/remove listeners in a way that works with AngularJS's scope.

socket.on / socket.addListener

Takes an event name and callback. Works just like the method of the same name from Socket.IO.

socket.removeListener

Takes an event name and callback. Works just like the method of the same name from Socket.IO.

socket.removeAllListeners

Takes an event name. Works just like the method of the same name from Socket.IO.

socket.emit

Sends a message to the server. Optionally takes a callback.

Works just like the method of the same name from Socket.IO.

socket.forward

socket.forward allows you to forward the events received by Socket.IO's socket to AngularJS's event system. You can then listen to the event with $scope.$on. By default, socket-forwarded events are namespaced with socket:.

The first argument is a string or array of strings listing the event names to be forwarded. The second argument is optional, and is the scope on which the events are to be broadcast. If an argument is not provided, it defaults to $rootScope. As a reminder, broadcasted events are propagated down to descendant scopes.

Examples

An easy way to make socket error events available across your app:

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  var mySocket = socketFactory();
  mySocket.forward('error');
  return mySocket;
});

// in one of your controllers
angular.module('myApp.MyCtrl', []).
  controller('MyCtrl', function ($scope) {
    $scope.$on('socket:error', function (ev, data) {

    });
  });

Avoid duplicating event handlers when a user navigates back and forth between routes:

angular.module('myMod', ['btford.socket-io']).
  controller('MyCtrl', function ($scope, socket) {
    socket.forward('someEvent', $scope);
    $scope.$on('socket:someEvent', function (ev, data) {
      $scope.theData = data;
    });
  });

socketFactory({ ioSocket: }}

This option allows you to provide the socket service with a Socket.IO socket object to be used internally. This is useful if you want to connect on a different path, or need to hold a reference to the Socket.IO socket object for use elsewhere.

angular.module('myApp', [
  'btford.socket-io'
]).
factory('mySocket', function (socketFactory) {
  var myIoSocket = io.connect('/some/path');

  mySocket = socketFactory({
    ioSocket: myIoSocket
  });

  return mySocket;
});

socketFactory({ scope: })

This option allows you to set the scope on which $broadcast is forwarded to when using the forward method. It defaults to $rootScope.

socketFactory({ prefix: })

The default prefix is socket:.

Example

To remove the prefix:

angular.module('myApp', [
  'btford.socket-io'
]).
config(function (socketFactoryProvider) {
  socketFactoryProvider.prefix('');
});

Migrating from 0.2 to 0.3

angular-socket-io version 0.3 changes X to make fewer assumptions about the lifecycle of the socket. Previously, the assumption was that your application has a single socket created at config time. While this holds for most apps I've seen, there's no reason you shouldn't be able to lazily create sockets, or have multiple connections.

In 0.2, angular-socket-io exposed a socket service. In 0.3, it instead exposes a socketFactory service which returns socket instances. Thus, getting the old API is as simple as making your own socket service with socketFactory. The examples below demonstrate how to do this.

Simple Example

In most cases, adding the following to your app should suffice:

// ...
factory('socket', function (socketFactory) {
  return socketFactory();
});
// ...

Example with Configuration

Before:

angular.module('myApp', [
  'btford.socket-io'
]).
config(function (socketFactoryProvider) {
  socketFactoryProvider.prefix('foo~');
  socketFactoryProvider.ioSocket(io.connect('/some/path'));
}).
controller('MyCtrl', function (socket) {
  socket.on('foo~bar', function () {
    $scope.bar = true;
  });
});

After:

angular.module('myApp', [
  'btford.socket-io'
]).
factory('socket', function (socketFactory) {
  return socketFactory({
    prefix: 'foo~',
    ioSocket: io.connect('/some/path')
  });
}).
controller('MyCtrl', function (socket) {
  socket.on('foo~bar', function () {
    $scope.bar = true;
  });
});

FAQ

Closed issues labelled FAQ might have the answer to your question.

See Also

License

MIT

angular-socket-io's People

Contributors

ajoslin avatar analogj avatar btford avatar dv336699 avatar jbpionnier avatar jkirkwood avatar meschbach avatar omarithawi avatar unao avatar waqasajaz avatar yocontra avatar zloydyadka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-socket-io's Issues

ReadMe is misguiding

When I tried to configure the socketProvider as explained in the doc I got an error message injector:modulerr.

angular.module('myApp', [
  'btford.socket-io'
]).
config(function (socketProvider) {
  socketProvider.prefix('');
});

When I tried socketFactoryProvider instead, the injector:modulerr error seems gone but the prefix and other methods mentioned in readme are undefined. I found the doc misguiding. Am I doing something wrong, how can I get it work ??

Crashes ionic app

hey i tried using this with ionic app but it crashes ionic app [on Android 4.0.4], but works fine in browser

have you tried this in ionic app
Can you pls try this with ionic app and confirm if i am doing something wrong and it is causing the crash and not this module.

socket.disconnect()

What is the correct approach to disconnect the client?

var mySocket = socketFactory({ioSocket: io.connect('http://localhost')}); 
mySocket.disconnect();       

gives the following error
TypeError: Object # has no method 'disconnect'

It works if instead of

var mySocket = socketFactory({ioSocket: io.connect('http://localhost')}); 

I use

var mySocket = io.connect('http://localhost'); 

If I understand correctly, socketFactory is a wrapper to angularify socket methods.
It exposes the following methods:on, addListener, emit, removeListener, forward.
It does not expose the socket.disconnect() method.

removeListener is not working due to anonymous listener function created by asyncAngularify

The current implementation of the asyncAngularify is problematic since removeListener should receive the exact function that was used when addListener was invoked.

example:
var myFunc = function myFunc(data){
//do something
}

socket.addListener('myEvent', myFunc);

so if i now call:

socket.removeListener('myEvent', myFunc);

this will not cause a removal of the listener and this is because asyncAngularify actually returns an unamed function, so in the actual socket.io 'myEvent' will have a listener like this:

function () {
var args = arguments;
$timeout(function () {
callback.apply(socket, args);
}, 0);
}

so it will never find myFunc and so will not remove it.

also you should only add named functions as listeners otherwise the current implementation of socket-client.io will not be able to remove unamed functions.

until you fix this issue i have added a removeAllListeners so i could delete all listeners for the mean time:

      removeAllListeners: function (eventName) {
        return socket.removeAllListeners(eventName);
      },

Forced build-time dep on ngmin

Basically, because angular-socket-io depends on ngmin for proper minification, using the development version to generate minified bundles oneself without using ngmin (e.g. the standard usage of RequireJS optimizer) will mess up the deps annotation. Surely one could disable the minification in requirejs, ngmin the requirejs output and subsequently minify, but it seems to be a little inconvenient. While ngmin is an awesome tool overall as described, it may or may not be desirable or usable for all. So what's the recommended solution to this? Documenting this caveat in README would help. I realize that you're the author of both libraries and certainly have pride in both; hence I'm not requesting removal of the dep but just documentation. Hell I'm just going to integrate ngmin into my (affected) project, and who I am to decide for your project!

Thanks a lot!

Socket.io + Sails + Resource

Dropping this here as requested:

I'm working with Sails.JS - which provides a REST API accessible either by standard HTTP or via a Socket.io connection.

I've managed to get the basic CRUD functionality working, as suggested in this issue : #13

The thing I'm having trouble with is how to extend this functionality out to a $resource type module. With sails, if you make a request like GET /api/foos -> you'll get an array of Foo objects returned, but you also get subscribed to any updates to the objects you've just fetched.

eg -

  • GET /foos -> returns [{id : 1, name : "foo1"},{id :2, name : "foo2"}]
  • Sails subscribes the socket to future updates to Foo models.
  • PUT /foos/1 {id: 1, name : "foo1updated"} -> returns OK
  • Sails broadcasts a "foo" event to all subscribed clients -> event : "foo", {verb : "updated", changed : {name : "foo1updated"}}

I have a basic wrapper around this module to simulate $resource - so I can effectively do Foo.query().then(function(foos){ }). The question is, how to link up the instantiated models so they listen for incoming model events, and apply/update the UI.

Make any sense at all?!

Socket wrapper : https://github.com/InnitApps/merchant-marine/blob/master/assets/js/innit/innit.core.io.js

Model wrapper : https://github.com/InnitApps/merchant-marine/blob/master/assets/js/innit/innit.core.model.js

io.connect undefined

When I try to do the following (almost verbatim from the example):

'use strict'

angular.module('MyModule', ['btford.socket-io'])
  .factory('Socket', ['socketFactory', 'accessTokenService', function(socketFactory, accessTokenService) {

        var ioSocket = io.connect('/', {  // error appears on this line
            query: 'token=' + accessTokenService.get()
        })

        return socketFactory({
            ioSocket: ioSocket
        })
    }]);

I get the following error:

TypeError: Cannot read property 'connect' of undefined

Which is strange, because (a) it was working before this, and (b) I definitely have included the socket-io.js script.

How can i reconnect ?

Hello.
I am developing chat app. and I have to reconnect after disconnect without reload page.
How can i do that?
help me, please...

regards,
kang

able to change Query for reconnect

just leave a simple access to socket object to able to change query for auto-reconnection

var wrappedSocket = {
          on: addListener,
    socket:socket,                     //this line
    addListener: addListener,
        once: addOnceListener,
...

example of using

this.socket.socket.socket.options.query = '?token='+user_token;

Require a method to update inner ioSocket object for connect / disconnect

In my app, I have both traditional http and websockets -- both are protected by JSON web token authentication. When a user logs in (i.e. post to http endpoint), a token is returned, and then the client will attempt to connect to the websocket endpoint with the token. The connection is rejected if the token isn't valid.

When a user logs out, the websocket is disconnected. I don't want to leave that channel open anymore b/c the user is no longer authenticated. Likewise, I don't want to re-use that same websocket if a new user logs in, b/c the authentication token will be different (and not valid for the new user).

What I'm left with is something like this:

angular.module('app.security')
   .factory('Socket', ['socketFactory', '$rootScope', function (socketFactory, $rootScope) {

      var socket, token = /* get token */

      function connect(token) {
         socket = io.connect('', { query: 'token=' + token, forceNew: true });
         socket.on('connect', function () { /* etc. */ });
         // other event handling
      }

      // connect if we have a token
      if (token) { connect(token); }

      $rootScope.on('login', function ( ) {
          token = /* get token */
          connect(token);
      });

      $rootScope.on('logout', function () { socket.disconnect(); })

      return socketFactory({ ioSocket: socket });
}]);

..and this is an example of how it is in injected into a controller to be used...

angular.module('app.something')
   .controller('FooCtrl', ['Socket', '$scope', function (Socket, $scope) {
      Socket.forward('time:request', $scope);
      $scope.$on('socket:time:response', function (evt, data) {
         console.log('the current time is ', data);
      });
      Socket.emit('time:request');
}]);

On login, the websocket is connected. On logout it is disconnected, and at the end, it is returning the socketFactory wrapper.

The problem here is that socketFactory.$get is only ever called once in the provider, which means that the very first time Socket is injected into a controller it is valid and connected. But if a user logs out and logs in again, angular re-injects the same instance into a controller, and the internal ioSocket has since been disconnected and is no longer good. (note the use of socket.io forceNew option which abandons the socket wholesale and initiates a brand new connection).

What is needed is something like the angular service recipe pattern which news up the object each time, so we don't re-use the same instance of the wrapper...either that or else an API exposed on socketFactory itself that allows one to replace the inner ioSocket reference.

Any ideas on the best way to accomplish this?

Examples are incorrect

config(function (socketProvider) {
  socketProvider.prefix('');

.........

There is no "socketProvider" provider. But instead, the provider "socketFactory" exists so the example
should be:

config 'socketFactoryProvider' ->
  socketFactoruProvider.prefix()

Also, socketFactoruProvider.prefix() method does not exist!

Issue specifying external socketio server

I realize this might be a dumb question, but I've been through the other posts on here and the docs a few times, and I haven't been able to figure out how to do it. How do I specify the location of the socket I want to connect to? I'm using an external service for the server side of my app, which is just an Express server with socketio.

I've tried setting it up in the config, so doing this:

config([function (socketFactory) {
  socketFactory.ioSocket(io.connect('http://website.com/some/path:443'));
})

But that's throwing an error, as socketFactory appears to be undefined. I'm using socketFactory instead of socketProvider because of #74, the example from the docs is also not working.

I suppose the first question should be, am I correct in thinking that this is where the server should be specified, or should it be done somewhere else? If this is the correct place to do it, what am I doing wrong?

Basically, I just want to be able to do this:

var socket = io('http://website.com/some/path:443');

The way I would in a standard socketio client.

The full code:

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'btford.socket-io']).
  config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider, socketFactory) {
      $routeProvider.
        when('/', {
          templateUrl: 'partials/index',
          controller: IndexCtrl
        }).
        when('/addPost', {
          templateUrl: 'partials/addPost',
          controller: AddPostCtrl
        }).
        when('/readPost/:id', {
          templateUrl: 'partials/readPost',
          controller: ReadPostCtrl
        }).
        when('/editPost/:id', {
          templateUrl: 'partials/editPost',
          controller: EditPostCtrl
        }).
        when('/deletePost/:id', {
          templateUrl: 'partials/deletePost',
          controller: DeletePostCtrl
        }).
        otherwise({
          redirectTo: '/'
        });
      $locationProvider.html5Mode(true);
      socketFactory.ioSocket(io.connect('http://website.com/some/path:443'));
    }
  ]).
  factory('socket', function (socketFactory) {
    var socket = socketFactory();
    return socket;
  }
);

I'm new to Angular (all of the routing stuff is coming from https://github.com/btford/angular-express-seed) so I imagine it's just something I'm not getting about the framework, but any help would be appreciated. Also, if it's not just an obvious error on my part, would it be possible to add a section on this to the docs, and/or correct the existing examples?

Edit:
I see that I did, in fact, miss something important in the docs. It appears that this is a way to do it:

  factory('socket', function (socketFactory) {
    var io_socket = io('https://my-notifications.com:443');
    var socket = socketFactory(io_socket);
    socket.forward('message');
    return socket;
  }

Now I just have to try to get forward working.

e2e testing with angular-socket-io should be possible

When setting up e2e tests for an angular app which uses angular-socket-io, it is currently not possible to test the outcome of asynchronous data updates received through the sockets. It would be very helpful to be able to wait for a socket-io service to receive test messages before running assertions in an angular scenario.

some troubles...

Error: [$injector:unpr] Unknown provider: socketProvider <- socket
http://errors.angularjs.org/1.2.16/$injector/unpr?p0=socketProvider%20%3C-

ocket
at http://localhost:4900/libs/angular/angular.js:78:12
at http://localhost:4900/libs/angular/angular.js:3705:19
at Object.getService as get
at http://localhost:4900/libs/angular/angular.js:3710:45
at getService (http://localhost:4900/libs/angular/angular.js:3832:39)
at invoke (http://localhost:4900/libs/angular/angular.js:3859:13)
at Object.instantiate (http://localhost:4900/libs/angular/angular.js:3880:23)
at http://localhost:4900/libs/angular/angular.js:7134:28
at link (http://localhost:4900/libs/angular/angular-route.js:913:26)
at nodeLinkFn (http://localhost:4900/libs/angular/angular.js:6579:13) angular.js:9778
(anonymous function) angular.js:9778
(anonymous function) angular.js:7216
nodeLinkFn angular.js:6582
compositeLinkFn angular.js:5986
publicLinkFn angular.js:5891
boundTranscludeFn angular.js:6005
controllersBoundTransclude angular.js:6600
update angular-route.js:871
Scope.$broadcast angular.js:12691
(anonymous function) angular-route.js:552
wrappedCallback angular.js:11319
wrappedCallback angular.js:11319
(anonymous function) angular.js:11405
Scope.$eval angular.js:12412
Scope.$digest angular.js:12224
Scope.$apply angular.js:12516
done angular.js:8204
completeRequest angular.js:8412
xhr.onreadystatechange angular.js:8351

Cannot connect to nodejs socket.io server

Hi.

I am testing out the socket.io implementation for angular, and have tested several ways to connect to the nodejs server I have. I also followed the documentation (to some extent), but I can't somehow connect when I run it. As default it's disconnected, could someone provide me a way to connect to the socket.io server?

This is the angular code I'm using when emitting etc.

factory('socket', function ($rootScope) {
    var socket = io.connect(URL HERE');
    console.log(socket);
    return {
        on: function (eventName, callback) {
            socket.on(eventName, function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            });
        }
    };
})

Thanks in advance!

Dependency error with minified socket factory

Compressed socket_factory.js on production gives the following error...
screen shot 2014-06-25 at 9 15 33 pm

This is the uncompressed socket_factory which works fine at development
websiteApp.factory('appSocket', ['socketFactory', function(socketFactory){
var appSocket = socketFactory();
appSocket.forward('error');
return appSocket;
}]);

This is the compressed socket_factory
websiteApp.factory("appSocket",["socketFactory",function(a){var b=a();return b.forward("error"),b}]);

What is going wrong?

changes not getting reflected on the other tab(or to other users)

Hi, really nice wrapper for socket-io. I just tried my hands on this but I am unable to pass the changes to the $scope in other instances of website running in the browser. I tried to make a simple facebook-ticker like feature by emitting a notification on a certain event like this

appSocket.emit('push:notification', {
    notification: message
});

and then listening for the event this way

appSocket.forward('push:notification', $scope);
$scope.$on('socket:push:notification', function(ev, data){
    $scope.notifications.push({"message": data.notification});
});

It works well on the same tab. But other running instances reflect no change.
Please help me get this sorted out.

"io is not defined" error when using MEAN.js

Hey everyone, I'm using [email protected] and I have made a gist of my angular controller here:
https://gist.github.com/skyserpent/832f980ca9ed9ed30e4b

My JS assets are loaded like this:
...
'//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js',
'public/lib/angular-socket-io/socket.js'

I have even included 'btford.socket-io' in Angular's 'applicationModuleVendorDependencies' but for some reason I get an error saying "io is not defined" in line 6 of the gist I uploaded.

Any help is much appreciated.

Error in ReadMe

The code snippets under 'Making a Socket Instance' and 'Using Your Socket Instance' appear to be identical.

Please, please tag this library with...

Angular.js, socket.io, duplicate data, multiple scopes.

The trouble with new technologies, no one knows what to search for in regards to a problem. After about 2 hours of looking I finally found this, please help out the next guy.

By the way, this library rocks, literal drop in replacement for the factory method I was using. And bonus points for actually solving the event bubbling issue.

transport=polling not found

I am trying to set up an express 4 server using socket.io and an angular frontend. I keep getting errors in the console and the browser about transport=polling not found.

In the terminal: GET /socket.io/?EIO=3&transport=polling&t=1411419424649-79 404 0.486 ms - 74

In the browser: Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1411419457464-84

What creates these errors?

Test example

@btford : Could you please had some examples about how to test it using Karma/jasmine ?

`emit()` arguments

I've been experiencing some strange problems when using the emit function with multiple data arguments.

For instance when I call

socket.emit('machines:getHwStatusUpdates', machineId, device, null,
  function(err, u) {...});

At the beginning of the emit function the arguments array looks as expected:

0: "machines:getHwStatusUpdates"
1: 16
2: "modem"
3: null
4: function (err, u) {

However, after var callback = arguments[lastIndex] is executed the arguments array is altered like this:

0: "machines:getHwStatusUpdates"
1: 16
2: function (err, u) {
3: null
4: function (err, u) {

It appears that callback defined in the function params still points to the arguments array during the function's execution, and is being updated by var callback = arguments[lastIndex].

Does this behavior make sense? Im using the latest version of Chrome on OS X.

What's strange is that I only have problems when I concat this file with my other js files. If I run this script without concating them, the arguments array is never altered.

Is this some strange js bug, or am I missing something here. Perhaps the parameters should be removed from the emit function altogether, since they are never referred to anyways? This seems to fix my problem:

emit: function () {
  var lastIndex = arguments.length - 1;
  var callback = arguments[lastIndex];
  if(typeof callback == 'function') {
    callback = asyncAngularify(socket, callback);
    arguments[lastIndex] = callback;
  }
  return socket.emit.apply(socket, arguments);
}

How to emit to a namespace

Hi,
I am new to Socket.io and want to integrate it to my angular project using your lib. I cannot find a way to emit to a specific namespace. In native Socket.io I guess I would do something like this:

socket.of('/namespace').emit(eventName, data, callback)

But there is no access to the "of" method or anything like that. Am I missing something or is this something I should add on my own?

Work with JWT's

Hello,
I am trying to make angular-socket.io work with an JWT Authentication system (using socketio-jwt and jsonwebtoken packages). I am using socket.io V1. I have the following angular service which sends the JWT as a query string. Socket authentication only works in my program when I log on and then hit F5. I am assuming this is because the Provider service wraps around the io() object and creates the socketFactory factory service when the program starts. Thus the factory Service is created before a user logs on and is given a JWT by the Node server. I have tried doing explicit refreshing and making other $http requests in the controller like:
$http.get("http://localhost:4000/socket.io/?token="+token")
$http.get("ws://localhost:4000/socket.io/?token="+token")
$window.location.reload();

How would angular-socket-io be hooked up to an authentication system where the io.connect querystring parameter varies with each login? Are there any examples?

angular.module('myApp.services', [])
.factory('socket', function (socketFactory, $rootScope, $window) {
  return socketFactory({
    ioSocket: io.connect('http://localhost:4000', {
      'force new connection': true, query: 'token=' + $window.sessionStorage.token
    })
  });
});

Many Thanks
Mick

io.connect() on injection

The moment I inject the socket service, the service calls io.connect() and fires off a call to my server at /socket.io/1?t=123456.

I need to connect my socket to a very specific route. I cannot see any other calls to to io.connect() in your code, so I'm a bit lost.

Have you provided a way to connect to an arbitrary path?

Connecting Over SSL

Is there any information on connecting over and SSL connection? Currently getting in the console:

Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.

Have the same setup as the readme file for this module. Any help would be appreciated.

Connecting after authentication

I have an angular app with a login form. Once authenticated my auth service will forward to the inner protected state of the Angular app. Within this, I would like to have the web socket open it's connection. Currently to achieve this I have to refresh the page after authenticating, then the socket connection occurs.

Do you have any recommendations on how to achieve this?

.forward only passes first parameter of event's data

// server side
socket.emit("event", "data1", "data2")

// client side
socket.forward("event", $scope);
$scope.$on("socket:event", function (scope, data1, data2) {
  console.log(data1); // "data1"
  console.log(data2); // undefined
});

I'd expect data2 to be defined in previous code sample. Is it a shared opinion?

Doesn't work with ng-strict-di

Currently angular-socket-io doesn't work with ng-strict-di. Following syntax should be used instead:

['dep1', 'dep2', function(dep1, dep2) { ... } ]

Examples are incorrect missing var

Hi Brian,
just to point out a missing var

factory('mySocket', function (socketFactory) {
    var myIoSocket = io.connect('/some/path');
    mySocket = socketFactory({
        ioSocket: myIoSocket
    });
   return mySocket;
});

should be

factory('mySocket', function (socketFactory) {
    var myIoSocket = io.connect('/some/path');
    var mySocket = socketFactory({
        ioSocket: myIoSocket
    });
   return mySocket;
});

my 2 cents :) bye

What is the correct way to clean up (destroy) a socket

I am trying to destroy the socket on $scope.$destroy, but I am still having sockets stack up when closing/opening a modal. I have tried socket.disconnect() but still see polling. I have been shutting the local socketio server to make sure that reconnect errors stop after the scope is destroyed but they continue and stack every time I re-open the modal.

What is the proper way to close/disconnect and dispose of sockets when leaving the modal/route where they were used?

Perceived Duplicates (Multiple controller instances)

Im getting dupplicates for every server->client event and ive done a project wide search for duplicate listeners, I think that maybe its because im passing in the root scope to the module? It happens for multiple events and im not using socket.forward. Thanks!

Access socket object

How do I access the socket object created in the factory, like mySocket.getSocket() so I can check if current status is connected and so on.

Socket.io 1.0 support

Hi i am using this plugin in an angular application with feathersjs as the back end. I use a branch with socket.io 1.0 and have been having an issue. will angular-socket.io work with socket.io 1.0 or do you need to do an upgrade.
Thanks

Cleaning up after event handlers after a scope is destroyed

Hi, Brian,

I wanted to trigger a discussion about whether the component should clean up after itself when scopes are destroyed, and if so, how it should go about doing so. For example, in a controller, you register some events with socket.on, and later that controller becomes inactive (maybe you switch to another route, etc.) or the scope gets destroyed for whatever reason, but the callbacks are still firing.

It's a bit of a pain to call $scope.$on('$destroy', ...) in every controller, not to mention that Socket.IO doesn't really present a way (that I'm aware of) to remove a set of callbacks--you either specify a single callback to remove (definitely a pain if there are several), or you remove them all (including ones not related to the current scope/controller).

I came across a StackOverflow question that brought up this issue, and after some thought I came up with this solution; I'm curious as to your thoughts on the matter. (Warning: beyond here be pseudo-code)

// A ScopedSocket is an object that provides `on` and `emit`
// methods, but keeps track of all listeners it registers
// on the socket. A call to `removeAllListeners` will remove
// all listeners on the socket that were created via this
// particular instance of ScopedSocket.

var ScopedSocket = function(socket, $rootScope) {
  this.socket = socket;
  this.$rootScope = $rootScope;
  this.listeners = [];
};

ScopedSocket.prototype.removeAllListeners = function() {
  // Remove each of the stored listeners
  for(var i = 0; i < this.listeners.length; i++) {
    var details = this.listeners[i];
    this.socket.removeListener(details.event, details.fn);
  };
};

ScopedSocket.prototype.on = function(event, callback) {
  var socket = this.socket;
  var $rootScope = this.$rootScope;

  // Store the event name and callback so we can remove it later
  this.listeners.push({event: event, fn: callback});

  socket.on(event, function() {
    var args = arguments;
    safeApply($rootScope, function() {
      callback.apply(socket, args);
    });
  });
};

ScopedSocket.prototype.emit = function(event, data, callback) {
  var socket = this.socket;
  var $rootScope = this.$rootScope;

  socket.emit(event, data, function() {
    var args = arguments;
    safeApply($rootScope, function() {
      if (callback) {
        callback.apply(socket, args);
      }
    });
  });
};

app.factory('Socket', function($rootScope) {
  var socket = io.connect();

  // When injected into controllers, etc., Socket is a function
  // that takes a Scope and returns a ScopedSocket wrapping the
  // global Socket.IO `socket` object. When the scope is destroyed,
  // it will call `removeAllListeners` on that ScopedSocket.
  return function(scope) {
    var scopedSocket = new ScopedSocket(socket, $rootScope);
    scope.$on('$destroy', function() {
      scopedSocket.removeAllListeners();
    });
    return scopedSocket;
  };
});

function MyController($scope, Socket) {
  var socket = Socket($scope);

  socket.on('message', function(data) {
     ...
  });
};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.