Singleton可配置提供程序,可访问cookie服务

时间:2014-04-09 08:00:13

标签: angularjs singleton angularjs-service

我已在我们的应用中为signalR创建了一个提供程序。我需要能够配置一次连接,然后根据需要附加功能。以下代码有效。除了一部分。 (我在代码示例中指出了这一点)

应用程序中的其他任何地方,当我想访问令牌时,我们使用角度cookie服务,但我无法在提供者内部这样做。作为一个快速的黑客,我添加了jquery cookie库来测试如果令牌确实存在我可以连接到我们的API。它确实...

问题

  

如何使用angular的服务/助手检索cookie /令牌?

提供商

   (function () {
        'use strict';

        angular.module('app').provider('signalrSvc', signalrSvc);

        function signalrSvc() {

            var self = this;

            self.hubs = [];

            this.start = function (hubs) {

                var connection = $.hubConnection("someurl/signalr");

                // convert hubNames to actual hub proxies, and append default client communication functions
                $.each(hubs, function (idx, hub) {
                    var proxy = connection.createHubProxy(hub);

                    // a minimum of one client function needs to be registered to be able to complete the connection
                    proxy.on('pingBack', function (data) { console.log(hub.hubName + ", connected: " + data); });

                    self.hubs[idx] = proxy;
                });

                // *********************THIS IS NOT "RIGHT"***********************//
                // add security token before attmpting connect
                $.ajaxPrefilter(function (options) {
                    if (!options.beforeSend) {
                        options.beforeSend = function (xhr) {
                            var token = $.cookie(".token").replace(/"/g,'');
                            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                        };
                    }
                });
                //***************************************************************//

                // connects and run initialise for each hub
                connection.start({ transport: 'longPolling' })
                    .done(function () {
                        $.each(self.hubs, function (idx, hub) {
                            hub.invoke('initialise');
                        });
                    });
            };

            this.$get = ['filterFilter', function (filterFilter) {
                return {
                    hub: function (name) {
                        return filterFilter(self.hubs, { hubName: name }, true)[0];
                    }
                };
            }
            ];
        }

    })();

配置

   app.config(['signalrSvcProvider', function (signalrSvcProvider) {
        signalrSvcProvider.start(['global','dashboard'], 'cookie');
    }]);

实施

   var hub = signalrSvc.hub('dashboard');

   hub.on('getAllUnapprovedAgreements', function (data) {
            // do something
   });

1 个答案:

答案 0 :(得分:0)

答案比我想象的要简单得多。使用合适的工具来做正确的工作。 IE 工厂。这允许我有一个连接/集线器集合,并允许我注入所需的服务

<强>代码

(function () {
    'use strict';

    angular.module('app').factory('signalrSvc', ['$rootScope', 'common', 'permissionSvc', 'filterFilter', signalrSvc]);

    function signalrSvc($scope, common, permissionSvc, filterFilter) {

        // assign placeholders. will be converted to actual hubs
        var hubs = ['globalHub', 'dashboardHub'];

        var connection = $.hubConnection(common.serviceUrl);

        // convert hubNames to actual hub proxies, and append default client communication functions
        angular.forEach(hubs, function (hub, idx) {
            var proxy = connection.createHubProxy(hub);

            // a minimum of one client function needs to be registered to be able to complete the connection
            proxy.on('pingBack', function (data) { console.log(proxy.hubName + ", connected: " + data); });

            proxy.subscribe = function (subscription, callback) {
                proxy.off(subscription);
                proxy.on(subscription,
                    function () {
                        var args = arguments;
                        $scope.$apply(function () {
                            callback.apply(proxy, args);
                        });
                    });
            };

            proxy.publish = function (target) {
                if ($.signalR.connectionState.connected) {
                    connection.start({ transport: 'longPolling' })
                              .done(function () {
                                  proxy.invoke(target);
                              });
                }
            };

            proxy.refresh = function (target) {
                if (target == undefined) {
                    proxy.publish('requestClientRefresh');
                } else {
                    proxy.publish(target);
                }
            };

            hubs[idx] = proxy;
        });

        // add security token before attmpting connect
        permissionSvc.createPrefilter();

        // connects and run initialise for each hub
        connection.start({ transport: 'longPolling' })
            .done(function () {
                angular.forEach(hubs, function (hub) {
                    hub.invoke('initialise');
                });
            });

        var publicFunctions = {
            hub: function (name) {
                return filterFilter(hubs, { hubName: name }, true)[0];
            }
        };

        return publicFunctions;
    };
})();