angularjs $httpProvider interceptor documentation

后端 未结 1 938
刺人心
刺人心 2020-12-25 15:25

I am new to angular (and programming), here is a seemingly simple question but I could not figure it out.

some tutorials suggests using $httpProvider.intercept

相关标签:
1条回答
  • 2020-12-25 16:04

    Interceptors are in the documentation here.

    Here's an example of how to write one.

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

    The reason there's nothing on the $httpProvider documentation page about interceptors is because the developers didn't include the following code in the $http script which the docs are generated from:

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

    Documentation in general is known to be incomplete, inaccurate, and/or confusing. Until recently, I always thought I was the problem when I couldn't find or understand something, but I've found that it's often because documentation is just lousy. However, we should all be thankful that we have such great tools to use and keep in mind that perhaps the documentation is poor because time had to be focused on writing the tool instead of the manual for the tool.

    The most reliable "documentation" is the source code itself, though it can be a lot less friendly to read! In the source code I linked above, you can see this.interceptors = []. this refers to the $httpProvider, so it is assigning the property interceptors to $httpProvider with the value being an empty array. To add your interceptors, you simply push() your interceptor to this array.

    0 讨论(0)
提交回复
热议问题