AngularJS $位置仅在WebSocket调用后第二次运行

时间:2015-11-05 14:28:09

标签: javascript angularjs websocket

在我的AngularJS应用程序中,我使用WebSocket连接应用程序和API。

我的问题是握手后我想将用户重新路由到新视图。这应该在调用成功后自动发生,这不会发生,但是如果我再次运行该函数它工作正常,这怎么可能?


错误:

Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.


控制器:

    ...
    $scope.signIn = function(){
        if($scope.loginForm.$valid){
            socketService.handshake($scope.login.username, $scope.login.password, function(response){
                if(response.payload.success){
                    $scope.user = $scope.login;
                    $scope.user.isLoggedIn = true;
                    $scope.user = sharedProperties.setUser($scope.user);

                    $scope.login = {};

                    $location.path('view/' + sharedProperties.getConfig().views[0].route);
                } else {
                    console.log('Error : Login failed');
                }
            });
        }
    };
    ...


SocketService:

    ...
    var service = {},
        socket;

    service.handshake = function(username, password, callback){
        handshake(username, password, function(response){
            callback(response);
        });
    };

    function handshake(username, password, callback){
        var jsonObject = {
                'agmt': '00001',
                'usr': username,
                'pwd': password,
                "request": 'INIT'
            };

        socket = new WebSocket(config.socketAddress);

        socket.onopen = function () {
            console.log("Server is on!");
            console.log('json', jsonObject);

            socket.send(JSON.stringify(jsonObject));
        };

        socket.onmessage = function (response) {
            console.log('\n' + new Date().toUTCString() + '\nServer responded');
            console.log('handshake data : ', response);

            callback(JSON.parse(response.data));
        };
    };
    ...

0 个答案:

没有答案