AngularJS 和 Websocket
AngularJS and Websocket
我正在尝试创建一个简单的回声测试应用程序,其中有连接和断开按钮。每当我点击连接时,我想创建一个 websocket 对象。我在服务中这样做。但不知何故,在创建一个对象后,onopen 并没有被解雇。我是新来的。有人能帮我吗?谢谢。
这是我的代码
HTML代码
<button class="echo-test-button" id ="connect" ng-click ="connect()">
Connect
</button>
<button class="echo-test-button" id ="disconnect" ng-click ="disconnect()">
Disconnect
</button>
控制器
var app = angular.module("test");
app.controller('SocketCtrl',["$scope","$window","Socket","$rootScope",
function ($scope, $window, socket, $rootScope) {
$scope.connect = function () {
socket.createConnection();
}
}]);
套接字服务
angular.module("test").factory("Socket",["$http","$q", function ($http, $q) {
var ws = {};
var socket = {
url : "ws://echo.websocket.org/",
};
socket.createConnection = function() {
ws = new WebSocket(socket.url);
};
ws.onopen = function (event) {
console.log("Established");
}
return socket;
}]);
您的 onopen 处理程序设置不正确。将 onopen 处理程序移到 createConnection 方法中。
angular.module("test").factory("Socket",["$http","$q", function ($http, $q) {
var ws = {};
var socket = {
url : "ws://echo.websocket.org/",
};
socket.createConnection = function() {
ws = new WebSocket(socket.url);
ws.onopen = function (event) {
console.log("Established");
}
};
return socket;
}]);
我正在尝试创建一个简单的回声测试应用程序,其中有连接和断开按钮。每当我点击连接时,我想创建一个 websocket 对象。我在服务中这样做。但不知何故,在创建一个对象后,onopen 并没有被解雇。我是新来的。有人能帮我吗?谢谢。 这是我的代码
HTML代码
<button class="echo-test-button" id ="connect" ng-click ="connect()">
Connect
</button>
<button class="echo-test-button" id ="disconnect" ng-click ="disconnect()">
Disconnect
</button>
控制器
var app = angular.module("test");
app.controller('SocketCtrl',["$scope","$window","Socket","$rootScope",
function ($scope, $window, socket, $rootScope) {
$scope.connect = function () {
socket.createConnection();
}
}]);
套接字服务
angular.module("test").factory("Socket",["$http","$q", function ($http, $q) {
var ws = {};
var socket = {
url : "ws://echo.websocket.org/",
};
socket.createConnection = function() {
ws = new WebSocket(socket.url);
};
ws.onopen = function (event) {
console.log("Established");
}
return socket;
}]);
您的 onopen 处理程序设置不正确。将 onopen 处理程序移到 createConnection 方法中。
angular.module("test").factory("Socket",["$http","$q", function ($http, $q) {
var ws = {};
var socket = {
url : "ws://echo.websocket.org/",
};
socket.createConnection = function() {
ws = new WebSocket(socket.url);
ws.onopen = function (event) {
console.log("Established");
}
};
return socket;
}]);