search

Home  >  Q&A  >  body text

angular.js - angular中如何设置全局的ajax请求?

需要给每次请求加上权限判断以及增加提示?小白问题大家请轻碰

迷茫迷茫2744 days ago565

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-05-15 16:52:14

    You'd better describe the problem in more detail, because the specific approach may vary depending on the situation.

    Generally speaking, if you just want to customize Headers, you can use $httpProvider.

    module.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.common['ANYTHING'] = 'YOU_NEEDED';
    }]);
    

    Please note that the headers of post, patch, put have their own independent configuration parts (common is shared by all methods). In addition, the configuration in module.config is only valid during initialization. If you need to modify it during operation, just $http service:

    $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
    

    If you want to uniformly handle requests, responses, request errors and response errors, you need to use Interceptors. The code of this example is too wordy, so I won’t write it. You can check the $http service document yourself. To put it simply, you can use factory to create custom interceptors, and then add them to $httpProvider.interceptors (which is an array), so that these interceptors act like middleware for each request All are handled uniformly.

    Finally, I have to say, either you describe the problem in more detail and accurately, or take the initiative to read the documentation. The documentation for $http and $httpProvider is only two pages, and everything you want to know is on it.

    reply
    0
  • Cancelreply