我需要两个AngularJS $http服务的实例呢?
我想为我的$ http服务添加一个响应拦截器以进行错误处理。拦截器逻辑包括在需要的情况下使用$ http向服务器发送错误消息,但是我不想向服务器发送有关错误消息的错误消息,我的意思是,我想要在向服务器发送错误消息时禁用我的拦截器。
我的想法是创建一个名为“remote_log”的服务,并将所有需要发送错误的代码放在服务器中。那个服务当然会使用$ http服务,并在它的依赖列表中。 然后将拦截器的依赖项添加到“remote_log”服务中,并在需要向服务器发送错误时使用拦截器内的“remote_log”。问题是: 当$ http服务仍未实例化/可访问时,拦截器必须使用$ httpProvider进行定义,因此,拦截器代码内不能依赖于$ http服务,因为“循环依赖”错误发生。 我认为我唯一的选择是在我的’remote_log’内创建一个单独的$ http服务实例,这个实例不会在创建拦截器时使用我设置的$ httpProvider配置。我的问题是:我该怎么做?任何其他想法?
循环依赖问题
那么为什么错误出现?以下是过程的快速概述: > $ http服务被请求。 第一个解决方案 使用angular.injector()创建您的依赖关系。请注意,您将创建另一个$ http服务,独立于您的应用程序。 $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. }); } }; }); 第二个解决方案(更好)。 在您的拦截器中注入$注射器,并使用它在$ http初始化之后检索依赖关系,就在您需要的时候。这些依赖关系是您的应用程序的注册服务,不会重新创建! $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. }); } }; }); 2.拦截预防问题。 如果您使用第二个解决方案,实际上有两个问题: >如果你使用$ http服务 $ http服务的’config’参数只是一个对象。您可以创建一个约定,提供自定义参数并在拦截器中识别它们。 例如,我们添加“nointercept”属性到配置,并尝试重复每个用户请求。这是一个愚蠢的应用程序,但有用的例子来了解行为: $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; } } }; }); 在拦截器中进行属性测试时,可能会阻止在控制器和服务中的拦截: 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) { // ... }); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |