angularjs $ httpProvider拦截器文档

时间:2014-10-03 01:17:40

标签: javascript angularjs http interceptor angular-services

我是角度(和编程)的新手,这是一个看似简单的问题,但我无法弄明白。

一些教程建议使用$httpProvider.interceptors.push('interceptorName')来操纵http请求和响应。

我想了解更多关于拦截器的事情所以我看一下官方文档,但我找不到任何与拦截器有关的东西,只有一个方法(useApplyAsync([value]);)和一个属性(默认值)在$httpProviderdocs)。

我从其他教程中知道拦截器是一个常规服务工厂,我知道如何使用它,但我的问题是:因为语法是$httpProvider.interceptors.push('interceptorName'),所以我希望我会找到一个叫做“拦截器”的属性“在$httpProvider中,但事实上我不能。我想念这个混乱的东西吗?或者我的概念从底层完全错了?

1 个答案:

答案 0 :(得分:24)

拦截器位于documentation here

以下是如何编写一个的示例。

.config([
  '$httpProvider',
  function($httpProvider) {

    var interceptor = [
      '$q',
      '$rootScope',
      'userSession',
      function($q, $rootScope, userSession) {

        var service = {

          // run this function before making requests
          'request': function(config) {

            if (config.method === 'GET' || userSession.isAuth()) {
              // the request looks good, so return the config
              return config;
            }

            // bad request, so reject
            return $q.reject(config);

          }

        };

        return service;

      }
    ];

    $httpProvider.interceptors.push(interceptor);

  }
])

关于拦截器的$httpProvider文档页面上没有任何内容的原因是因为开发人员未在$http script which the docs are generated from中包含以下代码:

/**
   * @ngdoc property
   * @name $httpProvider#interceptors
   * @description
// etc

一般而言,文档不完整,不准确和/或令人困惑。直到最近,当我找不到或理解某些东西时,我一直认为我是问题,但我发现这通常是因为文档只是糟糕。但是,我们都应该感谢我们有这么好的工具可以使用并记住,文档可能很差,因为时间必须集中在编写工具而不是工具的手册上。

最可靠的“文档”是源代码本身,尽管阅读起来可能不那么友好!在我上面链接的源代码中,您可以看到this.interceptors = []this引用$httpProvider,因此它将属性interceptors分配给$httpProvider,其值为空数组。要添加拦截器,只需将push()拦截器添加到此阵列。

相关问题