2

我正在通过第 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);
        }
    });
}]);
4

1 回答 1

0

If you need a global object (which is what a singleton is), why not simply attach an instance of it to the $rootScope?

That way you are sure what instance you are accessing, and won't have to work around Angular's service implementation.

于 2013-05-22T16:45:24.573 回答