4 番目の方法で単一の AngularJS サービスを作成しています。私のサービスは次のようになります...
provider('SocketService', {
socket: null,
// methods used within the config() of a module
connect: function(url) {
if (this.socket == null)
this.socket = portal.open('ws://production.local/socket/'+url);
},
// --------- Public methods for handling this socket -------------------------
$get: function() {
return {
getSocket: function() {
return this.socket;
},
on: function (event, handler) {
if (this.socket == null)
console.error('Unable to call .on() - Socket is not connected');
//if no handler is provided, "event" is an object of handlers...
if (handler == null)
return this.socket.on(event);
return this.socket.on(event, handler);
},
close: function () {
return this.socket.close();
}
};
}
});
this.socket
引き続きnull
$get メソッド内にあります。私のコントローラーは期待どおりにソケットを初期化しています...
config(['$routeProvider', 'SocketServiceProvider', function($routeProvider, SocketServiceProvider) {
//only initialize the socket when a URL in this route is accessed...
function initSocket() { SocketServiceProvider.connect('workstation/approval'); console.log('connected'); }
/* URL mappings */
$routeProvider.
when('/approval', {templateUrl: '/partials/loading.htm', controller: 'ApprovalCtrl', resolve: {socketInitializer: initSocket}}).
when('/approval/dashboard', {templateUrl: '/partials/approval/dashboard.htm', controller: 'ApprovalCtrl', resolve: {socketInitializer: initSocket}})
}]).
controller('ApprovalCtrl', ['$scope', '$cookieStore', 'WorkflowProcessService', 'WorkstationService', 'SocketService', 'socketUrl', '$location', function ($scope, $cookieStore, WorkflowProcessService, WorkstationService, SocketService, socketUrl, $location) {
/* Handle socket events coming from the server */
console.log(SocketService.getSocket()); //returns null
SocketService.on({
open: function () {
$scope.initializing.message = "Loading dashboard...";
$scope.showDashboard();
},
close: function (reason) {
$scope.initializing.status = true;
$scope.initializing.message = "Connection lost. Reconnecting...";
console.log(reason);
},
updateQueueSize: function (r) {
console.log(r);
}
});
}]);