【问题标题】:How to use two separate $http service instances in AngularJS?如何在 AngularJS 中使用两个单独的 $http 服务实例?
【发布时间】:2015-11-25 16:43:06
【问题描述】:

我正在实现一个 angularjs 服务,它将$http 调用发送的数据保存在localStorage 中。为此,我使用了请求拦截器,这样每当通过$http 发送http 请求时,数据就会保存在localStorage 中。下面是我的拦截器代码,

var OfflinkJs = angular.module('OfflinkJs', []);

OfflinkJs.factory('cacheInterceptor', function () {
    var cacheInterceptor = {
        request: function (config) {
            // Here I am saving the config as a string in localstorage
            return config;
        }
    };
    return cacheInterceptor;
});

为了让上面的拦截器工作,我必须在$httpProvider 的interceptors 数组中注册它。我这样做是为了实现这一点,

OfflinkJs.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('cacheInterceptor');
}]);

问题

现在,当我在另一个模块中使用OfflinkJS 模块时,所有$http 调用都会通过我的拦截器。但我想让$http 服务发送的一些请求使用我的拦截器,而其他一些请求NOT。

由于$http 服务是一个单例,我无法弄清楚如何在我的应用程序的不同位置使用它的两个实例。有什么方法可以实现吗?

我已经解决了这个问题,但似乎它确实解决了 循环依赖

I need two instances of AngularJS $http service or what?

【问题讨论】:

    标签: angularjs angular-http angular-http-interceptors


    【解决方案1】:

    我检查拦截器中的 URL 并使用它来过滤对其他服务的请求。我在我的模块中将我的服务的基本 url 设置为一个常量,然后检查它。如果请求不是针对相关服务的,则它只是通过而没有任何操作。

    但也许更好的方法是设置数据服务而不是拦截器。有很多关于数据服务的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 2021-01-20
      • 2014-10-04
      • 2012-11-03
      • 1970-01-01
      • 2018-06-28
      • 2013-01-22
      相关资源
      最近更新 更多