javascript - create global socket object in angular js? -
i new angular js , have requirement need create single instance of socket object can accessed controller.
for created factory private socket variable connects socket-io server automatically when application started. created public method return socket object.
i want know whether approach fine or can have better solution this.also imply create singleton object or not? below factory code wrote purpose. socketioservice.js
(function() { 'use strict'; angular .module('app.core') /* @nginject */ .factory('ncsocketfactory', function(socketfactory, call_url, $rootscope) { var socket = io.connect(call_url, { transports: ["websocket"] }); socket.on('connect', function () { console.log('socket io connected...'); $rootscope.$broadcast('socket:connected'); }); socket.on('incomingcall', function (data,evt) { console.log('incomingcall data..'+data); $rootscope.incomingcalldata = data; $rootscope.$broadcast('socket:incomingvideocall'); }); socket.on('disconnect', function () { console.log('socket io disconnected...'); $rootscope.$broadcast('socket:disconnected'); }); return { getsocketobject: function(){ return socket; }, on: function (eventname, callback) { socket.on(eventname, function () { }); }, emit: function (eventname, data, callback) { socket.emit(eventname, data, function () { }); }, reconnect: function () { socket = io.connect(call_url, { transports: ["websocket"] }); }, disconnect: function () { console.log('in socket disconnect:'+socket.connected); if(socket.connected){ socket.disconnect(); console.log('ncsocketfactory disconnected'); } } }; }); })();
Comments
Post a Comment