AngularJS socket.io事件与递延承诺转发 [英] AngularJS socket.io event forwarding with deferred promise

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

问题描述

我使用角插座-IO 但需要一种方法的验证应用程序首先启动socket.io接口之前。 我跟着这个方法

但我需要使用事件转发在工厂如下所示是这样的:

  socket.forward(事件);

我如何加入我厂转发?

  .factory('插座',函数($ rootScope,$超时的SocketFactory,$ Q $日志){
  //创建一个承诺实例
  变种插座= $ q.defer();
  //侦听的rootScope发出的认证活动
  //将角应用。一旦事件被触发,创建套接字和解决
  // 承诺。
  $ rootScope。在$('认证',函数(){    //决心另一个摘要周期
    $超时(函数(){
      VAR令牌= window.localStorage [socket_token];
      VAR token_query ='令牌='+令牌;
      VAR newSocket =(函数(){
        返回的SocketFactory({
          ioSocket:io.connect('http://example.com:3000',{
            查询:token_query
          })
        });
      })();
      socket.resolve(newSocket);
    });
  });
  返回socket.promise
});


解决方案

您可以简单地将呼叫添加到向前()之前解决与创建的插座承诺:

  newSocket =(函数(){/ * ... * /})()
newSocket.forward(事件);
socket.resolve(newSocket);

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

解决方案

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天全站免登陆