AngularJS socket.io 延迟承诺的事件转发
AngularJS socket.io event forwarding with deferred promise
我正在使用 angular-socket-io but needed a way to authenticate in the app first before starting the socket.io interface. I followed this method。
但是我需要像这样在工厂中使用事件转发as shown here:
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);
我正在使用 angular-socket-io but needed a way to authenticate in the app first before starting the socket.io interface. I followed this method。
但是我需要像这样在工厂中使用事件转发as shown here:
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);