如何从$ httpProvider调用服务

时间:2014-07-25 11:03:07

标签: angularjs angularjs-service

我整个上午一直在努力解决这个问题。我试图从我的配置中调用服务($ httpprovider)。我已经阅读了很多人,他们解释说在配置期间服务尚未可用。我明白了,但我的服务只能在拦截器内调用,这是在运行时。

我找到了一个手动注入服务的半解决方案,如下所示,但它对我不起作用,因为它似乎正在创建一个全新的服务实例,我想继续使用整个app中的相同实例(因为它存储了一个messageQueue数组)。有什么建议吗?

.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push(function ($q) {
            return {
                'responseError': function (rejection) {
                    //responses 300 and up are errors
                    //Manually inject service from the myServices module, since it is not yet known when .config is called
                    var $injector = window.angular.injector(['myServices']);
                    var MessageService = $injector.get('MessageService');
                    MessageService.setMessage("We were unable to load all necessary data. We're terribly sorry! Please try reloading this page or contact us if the problem isn't solved.");
                }
            };
        });
    }])

1 个答案:

答案 0 :(得分:0)

根据angularjs 1.2.2 documentation,您可以使用工厂将拦截器注册为服务,因此应使用以下语法为其提供正确的依赖关系:

.config(['$httpProvider', function ($httpProvider) {

    $provide.factory('myHttpInterceptor', ['MessageService', function (MessageService) {
        return {
            'responseError': function (rejection) {
                //responses 300 and up are errors
                MessageService.setMessage("We were unable to load all necessary data. We're terribly sorry! Please try reloading this page or contact us if the problem isn't solved.");
            }
        };
    }]);

    $httpProvider.interceptors.push('myHttpInterceptor');
}]);