带有延迟承诺的 AngularJS socket.io 事件转发 [英] AngularJS socket.io event forwarding with deferred promise

查看:19
本文介绍了带有延迟承诺的 AngularJS socket.io 事件转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular-socket-io 但需要一种在app 在启动 socket.io 接口之前.我按照这个方法.

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

推荐答案

在使用创建的套接字解​​析 promise 之前,您可以简单地添加对 forward() 的调用:

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

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

这篇关于带有延迟承诺的 AngularJS socket.io 事件转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆