AngularJS socket.io event forwarding with deferred

2019-07-18 04:57发布

问题:

I am using angular-socket-io but needed a way to authenticate in the app first before starting the socket.io interface. I followed this method.

But I need to use event forwarding in the factory as shown here like this:

socket.forward("event");

How can I add forwarding in my factory?

.factory('socket', function($rootScope, $timeout, socketFactory, $q, $log) {
  // create a promise instance
  var socket = $q.defer();
  // listen for the authenticated event emitted on the rootScope of
  // the Angular app. Once the event is fired, create the socket and resolve
  // the promise.
  $rootScope.$on('authenticated', function() {

    // resolve in another digest cycle
    $timeout(function() {
      var token = window.localStorage["socket_token"];
      var token_query = 'token=' + token;
      var newSocket = (function() {
        return socketFactory({
          ioSocket: io.connect('http://example.com:3000', {
            query: token_query
          })
        });
      })();
      socket.resolve(newSocket);
    });
  });
  return socket.promise
});

回答1:

You can simply add the call to forward() before resolving the promise with the created socket:

newSocket = (function() { /* ... */ })()
newSocket.forward("event");
socket.resolve(newSocket);