首页 > 代码库 > angularJS socket
angularJS socket
项目Controller文件中加载Service层socket.js.页面进入该controller所在页面时连接socket(也可一进入项目就连接,看需求),细节还需继续优化,写下来以防忘了~
Service层:socket.js
/************************************************************* ******************Angular Websocket Service****************** ******************author:ristal****************************** ******************created:2014-04-01**************************/ angular.module('websocketService', []) .service('sWSocket', ['$timeout', function ($timeout) { var self = this; var callbackPool = []; //onMessage分类处理函数 var delayPool = []; //延迟处理请求 var registerPool = [];//已注册的方法 var data = http://www.mamicode.com/{};>Controller层:<pre name="code" class="javascript">/************************************************************* ******************Angular Websocket Controller**************** ******************author:ristal****************************** ******************created:2014-04-01**************************/ angular.module('websocketControllers') .controller('loginCtrl', function ($scope,loginFactory,sWSocket,toaster,$location,$timeout) { console.log("loginCtrl"); $scope.status; var appId = 'heartBeat'; var methodId = 'heartBeat'; var callback = function(evendata){ console.log("callback:",evendata); $scope.menu = evendata; $scope.$apply(); console.log($scope.menu); } var callback1 = function(evendata){ console.log("callback1:",evendata); $scope.menu = evendata; $scope.$apply(); console.log($scope.menu); } $scope.doLogin = function(user){ loginFactory.doLogin(user) .success(function (success) { if(success.resultCode == 200){ $scope.status = '登录成功'; console.log("doLogin"); $location.path('/home'); var content2 = { userName:'hmm', userPassword:'111' }; //websocket登陆 sWSocket.send('login', 'doLogin', content2); //考虑极端情况,一个页面有多个模块监听同一个方法 //但展示在页面的数据需对接收的实时监听的数据做不同处理 //登陆后注册方法heartBeat,回调函数callback //页面切换时(也就是注销scope时)才注销此方法 sWSocket.register(appId,methodId,callback); //登陆后也注册方法heartBeat,回调函数callback1 //3s后立即注销此方法 sWSocket.register(appId,methodId, callback1); $timeout(function () { console.log("unregister callback1"); sWSocket.unregister(appId,methodId,callback1); }, 3000); }else if (success.resultCode == 102) { toaster.pop('error', "操作失败", success.resultReason); $scope.status = success.resultReason; }; }) .error(function (error) { $scope.status = '登录失败: ' + error.message; }); }; $scope.logout = function(){ loginFactory.logout() .success(function () { $scope.status = '退出成功'; console.log("logout"); }) .error(function (error) { $scope.status = '退出失败: ' + error.message; }); }; //注销scope时注销方法heartBeat,回调函数callback $scope.$on("$destroy",function(){ console.log("on-destroy"); sWSocket.unregister(appId,methodId,callback); }); });
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。