问题
After solving this issue I now have a new issue with angular halting inside a function that's waiting on a socket connection.
Controller:
.controller('myCtrl',function($scope, socket) {
var sendMsg = function(msg) {
socket.then(function(msg) {
socket.emit('newMsg', msg);
});
}
//simplified example
var msg = 'Hi Mom!';
sendMsg(msg);
});
The problem is that socket.emit()
never gets fired. If I remove socket.then()
I will get an error socket.emit is not a function
. We have to wait for socket to be initialized (which is based on successful login in another controller and broadcast through the socket
factory). Is this a chicken-egg paradox? How can I fire socket.emit in another function? Other similar functions work, such as:
socket.then(function(socket) {
socket.on('connect',function() {
//do something. This works.
});
});
回答1:
The problem seems to be that you are having two msg
parameters. However, the second one is the socket:
var sendMsg = function(msg) {
socket.then(function(socket) { // <--
socket.emit('newMsg', msg);
});
}
来源:https://stackoverflow.com/questions/35044402/angularjs-not-executing-deferred-promise-using-angular-socket-io