我需要两个 AngularJS $http 服务实例还是什么? [英] I need two instances of AngularJS $http service or what?

查看:28
本文介绍了我需要两个 AngularJS $http 服务实例还是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 $http 服务添加一个响应拦截器以进行错误处理.拦截器逻辑包括在必要时使用 $http 向服务器发送错误消息,但是我不想向服务器发送关于错误消息的错误消息,我的意思是,我想在发送错误时禁用我的拦截器向服务器发送消息.

I want add a response interceptor to my $http service for error handling purposes. The interceptor logic include send errors messages to server using $http in case necessary, BUT I don't want send errors messages to the server about errors messages, I mean, I want disable my interceptor while sending error message to the server.

我的想法是创建一个名为remote_log"的服务,并将向服务器发送错误所需的所有代码放入其中.该服务当然将使用 $http 服务并将其包含在其依赖项列表中.

My idea was create a service named 'remote_log' and put inside it all the code needed to send error to server. That service of course will use the $http service and have it in its dependency list.

然后将拦截器的依赖添加到'remote_log'服务中,并在需要向服务器发送错误时使用拦截器内部的'remote_log'.问题在于:

Then add as dependency of the interceptor to the 'remote_log' service, and use the 'remote_log' inside the interceptor when need send errors to the server. The problems is that:

当 $http 服务仍未实例化/可访问时,必须使用 $httpProvider 定义拦截器,因此,拦截器代码内部不能依赖于 $http 服务,因为会发生循环依赖"错误.

Interceptors must be defined using the $httpProvider when the $http service still is not instantiated/accessible, so, inside the interceptor code can't be a dependency to that the $http service because a "Circular dependency" error happen.

我认为我唯一的选择是在我的remote_log"中创建一个单独的 $http 服务实例,该实例不使用我在创建拦截器时设置的 $httpProvider 配置.我的问题是:我该怎么做?还有其他想法吗?

I think my only option is create a separate instance of the $http service inside my 'remote_log', an instance that don't uses the $httpProvider configuration I set while creating the interceptor. My question is: How can I do that? Any other ideas?

推荐答案

1.循环依赖问题.

那么,为什么会出现这个错误呢?以下是该过程的简要概述:

1. Circular dependency problem.

So, why does the error appear? Here is a quick overview of the process:

  1. 已请求 $http 服务.
  2. $httpProvider 被要求构建它.
  3. 在构建过程中,您注册了拦截器,该拦截器请求的 $http 服务尚不存在.
  4. 您收到循环依赖"错误.


使用 angular.injector() 创建您的依赖项.请注意,您将创建另一个独立于您的应用的 $http 服务.

Create your dependency using angular.injector(). Notice, that you will create another $http service, independent from your app.

$httpProvider.interceptors.push(function($q) {
    $injector = angular.injector();
    return {
        response: function(response) {
            $injector.invoke(function($http) {
                // This is the exterior $http service!
                // This interceptor will not affect it.
            });
        }
    };
});


在您的拦截器中注入 $injector 并在 $http 初始化后使用它来检索依赖项,就在您需要它们的时候.这些依赖项是您应用的注册服务,不会重新创建!

Inject $injector in your interceptor and use it to retrieve dependencies after $http initialization, right at the time you need them. These dependencies are registered services of your app and will not be created anew!

$httpProvider.interceptors.push(function($q, $injector) {
    return {
        response: function(response) {
            $injector.invoke(function($http, someService) {
                // $http is already constructed at the time and you may
                // use it, just as any other service registered in your
                // app module and modules on which app depends on.
            });
        }
    };
});


如果使用第二种方案,其实有两个问题:

If you use the second solution, there are actually two problems:

  1. 如果您在内部使用 $http 服务拦截器,你可能会得到无限拦截:你发送请求,拦截器捕获它,发送另一个,捕获另一个,再次发送,依此类推.
  2. 有时您只想防止请求被拦截.

$http 服务的 'config' 参数只是一个对象.您可以创建一个约定,提供自定义参数并在您的拦截器中识别它们.

The 'config' parameter of $http service is just an object. You may create a convention, providing custom parameters and recognizing them in your interceptors.

例如,让我们在配置中添加nointercept"属性并尝试复制每个用户请求.这是一个愚蠢的应用程序,但有助于理解行为的示例:

For example, let's add "nointercept" property to config and try duplicate every user request. This is a silly application, but useful example to understand the behavior:

$httpProvider.interceptors.push(function($q, $injector) {
    return {
        response: function(response) {
            if (response.config.nointercept) {
                return $q.when(response); // let it pass
            } else {
                var defer = $q.defer();
                $injector.invoke(function($http) {
                    // This modification prevents interception:
                    response.config.nointercept = true;
                    // Reuse modified config and send the same request again:
                    $http(response.config)
                        .then(function(resp) { defer.resolve(resp); },
                              function(resp) { defer.reject(resp); });
                });
                return defer.promise;
            }
        }
    };
});

在拦截器中进行属性测试,可以防止控制器和服务中的拦截:

Having the testing for property in interceptor, you may prevent the interception in controllers and services:

app.controller('myController', function($http) {
    // The second parameter is actually 'config', see API docs.
    // This query will not be duplicated by the interceptor.
    $http.get('/foo/bar', {nointercept: true})
        .success(function(data) {
            // ...
        });

});

这篇关于我需要两个 AngularJS $http 服务实例还是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆