使用AngularJS中的promises和WebSockets

时间:2016-03-25 09:58:25

标签: javascript angularjs websocket angular-promise

我有这个JS代码:

app.factory('ChatWebsocket', function ($q, ChatSocketUrl)
{
    var socket = new WebSocket(ChatSocketUrl);

    return $q(function (resolve, reject) {
        socket.onopen = function () {
            resolve(socket);
        };
        socket.onerror = function (e) {
            reject(e);
        }
    });
});

app.factory('ChatServiceWebsocket', function ($q, ChatWebsocket)
{
    function SocketWrapper(socket, action, payload)
    {
        return $q(function (resolve) {
            socket.onmessage = function (e) {
                resolve(JSON.parse(e.data));
            };

            socket.send(JSON.stringify({action: action, payload: payload}));
        });
    }

    return {
        login: function (userId, subjectId) {
            return ChatWebsocket.then(function (socket) {
                return new SocketWrapper(socket, 'login', {user: userId, subject: subjectId});
            });
        },
        rooms: function (userId) {
            return ChatWebsocket.then(function (socket) {
                return new SocketWrapper(socket, 'rooms', {user: userId});
            });
        }
    };
});


/******************* THE CONTROLLER ***************************/

ChatServiceWebsocket.rooms(userId).then(function (result) {
    console.log('ChatServiceWebsocket.rooms = ', result);
});

ChatServiceWebsocket.login(userId, roomId).then(function (result) {
    console.log('ChatServiceWebsocket.login = ', result);
});

我期待在控制台中看到:

ChatServiceWebsocket.rooms = [Object ... room list]
ChatServiceWebsocket.login = [Object ... login data]

但我只看到最后一次通话,输出无效:

ChatServiceWebsocket.login = [Object ... room list]

无法使此ChatServiceWebsocket正常工作:(

0 个答案:

没有答案