Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了我需要两个AngularJS $http服务的实例呢?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想为我的$ http服务添加一个响应拦截器以进行错误处理。拦截器逻辑包括在需要的情况下使用$ http向服务器发送错误消息,但是我不想向服务器发送有关错误消息的错误消息,我的意思是,我想要在向服务器发送错误消息时禁用我的拦截器。

我的想法是创建一个名为“remote_log”的服务,并将所有需要发送错误代码放在服务器中。那个服务当然会使用$ http服务,并在它的依赖列表中。

然后将拦截器的依赖项添加到“remote_log”服务中,并在需要向服务器发送错误时使用拦截器内的“remote_log”。问题是:

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

我认为我唯一的选择是在我的’remote_log’内创建一个单独的$ http服务实例,这个实例不会在创建拦截器时使用我设置的$ httpProvider配置。我的问题是:我该怎么做?任何其他想法?

循环依赖问题

那么为什么错误出现?以下是过程的快速概述:

> $ http服务被请求。
> $ httpProvider被要求构造它。
>在建设过程中你注册拦截器,它要求$ http服务尚未存在。
>你得到“循环依赖”错误

一个解决方

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

@H_502_24@$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初始化之后检索依赖关系,就在您需要的时候。这些依赖关系是您的应用程序的注册服务,不会重新创建!

@H_502_24@$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”属性到配置,并尝试重复每个用户请求。这是一个愚蠢的应用程序,但有用的例子来了解行为:

@H_502_24@$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; } } }; });

拦截器中进行属性测试时,可能会阻止在控制器和服务中的拦截

@H_502_24@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服务的实例呢?全部内容,希望文章能够帮你解决我需要两个AngularJS $http服务的实例呢?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: