Add common parameter in each http request

2019-06-05 08:14发布

Suppose that all of my Rest API need to accept following parameters:
1) param1
2) param2

It would be tedious for me to implement this way (refer to code right below). Moreover, it defies the concept of DRY. What I am looking for is a global configuration that allows default parameter to be passed along with the http request.

I believe that $httpProvider is the closest i can get (since it can define cookie expiry, header etc globally) but it seems that i could not find the way of using it to pass parameters.

angular.module('myApp.services').factory('Entry', function($resource) {
  return {
      method1: $resource('/api/entries/:id/:param1/:param2',
      { id: '@_id', param1:'@param1', param2: '@param2'}, {
        update: {
          method: 'PUT' // this method issues a PUT request
        }
      }),
      method2: $resource('/api/entries2/:param1/:param2',
      {param1:'@param1', param2: '@param2'}, {

      })
});

I expect something like this from the final optimize code.

angular.module('myApp.services').config($httpProvider){
    $httpProvider.defaults.param('param1');
    $httpProvider.defaults.param('param2');
}


angular.module('myApp.services').factory('Entry', function($resource) {
  return {
      method1: $resource('/api/entries/:id/',
      { id: '@_id' }, {
        update: {
          method: 'PUT' // this method issues a PUT request
        }
      }),
      method2: $resource('/api/entries2'),
      {}, {

      })
});

1条回答
女痞
2楼-- · 2019-06-05 08:37

You have to create an interceptor service and then add the interceptor to the $httpProvider in your app.config().

Create your interceptor service:

angular.module('app').factory('myInterceptorService', myInterceptorService);

function myInterceptorService(){
   var param1,param2;
   return{
       request:  requestInterceptor,
       setParams:  setParams
  };
  function requestInterceptor(config){
       config.params.push(param1);
       config.params.push(param2);
       return config;
  }
  function setParams(p1,p2){
       param1=p1;
       param2=p2;
  }
}

To register with app config, add $httpProvider to app.config

app.config([...,'$httpProvider'...){
    $httpProvider.interceptor.push('myInterceptorService');
}
查看更多
登录 后发表回答