在每个http请求中添加通用参数 [英] Add common parameter in each http request

查看:466
本文介绍了在每个http请求中添加通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我所有的Rest API都需要接受以下参数:
1)param1
2)param2

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

以这种方式实现(对下面的代码而言)对我来说是很麻烦的. 此外,它违反了DRY的概念.我要寻找的是一个全局配置,该配置允许将默认参数与http请求一起传递.

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.

我相信 $ httpProvider 是我可以获得的最接近的(因为它可以全局定义cookie到期时间,标头等),但似乎找不到使用它传递参数的方法.

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'),
      {}, {

      })
});

推荐答案

您必须创建一个拦截器服务,然后将该拦截器添加到app.config()中的$ httpProvider中.

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

创建拦截器服务:

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;
  }
}

要向app config注册,请将$ httpProvider添加到app.config

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

app.config([...,'$httpProvider'...){
    $httpProvider.interceptor.push('myInterceptorService');
}

这篇关于在每个http请求中添加通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆