我正在使用angular-socket-io,但在启动 socket.io 界面之前,需要一种先在应用程序中进行身份验证的方法。我遵循了这种方法。
但是我需要在工厂中使用事件转发,如下所示:
socket.forward("event");
如何在工厂中添加转发?
.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
});
在用创建的套接字解析承诺之前,您只需将调用添加到forward()
:
newSocket = (function() { /* ... */ })()
newSocket.forward("event");
socket.resolve(newSocket);