angularjs $ httpProvider拦截器文档

web*_*uma 15 javascript http interceptor angularjs angular-services

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

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

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

我从其他教程中知道拦截器是一个常规服务工厂,我知道如何使用它,但我的问题是:因为语法是$httpProvider.interceptors.push('interceptorName'),然后我希望我会找到一个名为"拦截器"的属性$httpProvider,但实际上我可以"T.我想念这个混乱的东西吗?或者我的概念从底部是完全错误的?

m59*_*m59 24

拦截器在这里文档中.

这是一个如何编写一个的例子.

.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);

  }
])
Run Code Online (Sandbox Code Playgroud)

$httpProvider文档页面上没有关于拦截器的原因是因为开发人员没有在$http生成文档脚本中包含以下代码:

/**
   * @ngdoc property
   * @name $httpProvider#interceptors
   * @description
// etc
Run Code Online (Sandbox Code Playgroud)

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

最可靠的"文档"是源代码本身,尽管阅读起来可能不那么友好!在上面链接的源代码中,您可以看到this.interceptors = [].this指的是$httpProvider,因此被分配属性interceptors,以$httpProvider与所述值是一个空数组.要添加拦截器,只需push()将拦截器添加到此阵列即可.

  • 感谢您更新答案,现在它看起来很完美,因为它清楚地解释并提供了文档的总体情况.在阅读完答案后,任何像我这样的初学者都会对编码感到沮丧和自信 (2认同)