Angular中的拦截器,仅用于某些调用?

时间:2016-03-23 09:02:13

标签: angularjs

我的Angular App中有以下工厂。它用于通过$ resource将持有者令牌信息添加到我所有传出请求的标头中。它按预期工作。

但是我已经实现了一些外部呼叫,不应该使用承载令牌添加。我如何实施支票,以便我可以控制哪些电话被拦截而哪些不被拦截?

我的代码:

.factory('authInterceptor', [
      "$q", "$window", "$location", "currentUser", function ($q, $window, $location, currentUser) {
          return {
              request: function(config) {
                  config.headers = config.headers || {};
                  config.headers.Authorization = 'Bearer ' + currentUser.getProfile().token;
                  return config;
              },
              response: function(response) {
                  return response || $q.when(response);
              },
              responseError: function(rejection) {
                  // error handler
              }
          };
      }
    ])

添加authInterceptor:

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

资源工厂:

myApp.factory('Random', function ($resource) {
    return $resource('domain.com', { }, {
        update: {
            method: 'PUT'
        }
    });
});

调用资源:

Random.query({ });

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

有很多方法,例如,您可以在请求对象中执行某些操作,

    .factory('authInterceptor', [
          "$q", "$window", "$location", "currentUser", function ($q, $window, $location, currentUser) {
              return {
                  request: function(config) {
if(config.url !== 'external url') {
                      config.headers = config.headers || {};
                      config.headers.Authorization = 'Bearer ' + currentUser.getProfile().token;
}
                      return config;
                  },
                  response: function(response) {
                      return response || $q.when(response);
                  },
                  responseError: function(rejection) {
                      // error handler
                  }
              };
          }
        ])

使用该条件,您将跳过不需要的网址mod 查看文档, https://docs.angularjs.org/api/ng/service/ $ HTTP使用# 您甚至可以为所有呼叫创建一个密钥,用于打开/关闭拦截。

相关问题