AngularJS socket.io event forwarding with deferred promise

纵然是瞬间 提交于 2019-12-23 22:18:33

问题


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);


来源:https://stackoverflow.com/questions/35006814/angularjs-socket-io-event-forwarding-with-deferred-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!