angular.js - angularjs ngResource 如何设置所有请求的header?
phpcn_u1582
phpcn_u1582 2017-05-15 17:00:27
0
3
799

我想在每个请求中都会提交一个header,类似于 a: bbb 这样的内容.

    // 无论是获取列表
    $scope.books = myRes.query();
    // 还是单独的一个项目
    $scope.oneBook = myRes.get({id:2});

能在所有的RESTful这样的请求中加入一个header,header的内容是

    ca-g-oo: data-dnwaec2ioagwqevnm

尝试了各种方式都无法实现

$resource(url, [paramDefaults], [actions]);

url是设置请求的地址
paramDefaults是预设的要提交的数据
action是自定义的函数方法

感觉可以通过action来设置,但是不行

    // 如果把action设置成这样
    $resource(
        'ca/book/:id',
        {},
        {
            query: {
                header: {
                    "ca-g-oo": "data-dnwaec2ioagwqevnm"
                }
            },
            get: {
                header: {
                    "ca-g-oo": "data-dnwaec2ioagwqevnm"
                }
            }
        }
    );

就报错了

    Error: [$resource:badcfg] http://errors.angularjs.org/1.2.29/$resource/badcfg?p0=object&p1=array

我要如何设置$resource的才能让所有的请求的带着我自定义的header啊?

phpcn_u1582
phpcn_u1582

reply all(3)
習慣沉默

interreputor can satisfy you

滿天的星座

The problem is also solved. . When setting $resource, set the isArray attribute

isArray property


The complete code is as follows

'amd';
/**
 * 
 * RESTful创建服务
 * by chenxuan 20160325
 *
 * 创建一个$resource对象
 * query : 获取列表
 * get : 获取单个数据
 * updata : 更新数据
 * save : 新建数据保存
 *
 * 关于缓存
 * 默认缓存query和get请求,当有updata和save请求产生的时候清空所有缓存
 *
 * ====v1.1====20160328
 * functionSetting参数的对象不会直接覆盖没有在对象中存在的默认属性
 * 
 */
define(
    [
        'app'
    ],
    function (app){
        app.factory('RESTful', function ($resource,$cacheFactory){
            return function (url, defaultParam, functionSetting){
                var RESTfulCacheID = "" + Math.random();
                var RESTfulCache = $cacheFactory(RESTfulCacheID, {capacity: 10});
                var defaultFunction = {
                    query: {
                        method: 'GET',
                        isArray: true,
                        headers: {
                            'X-CSRF-TOKEN': app.CSRF_TOKEN
                        },
                        cache: RESTfulCache
                    },
                    get: {
                        method:'GET',
                        isArray: false,
                        headers: {
                            'X-CSRF-TOKEN': app.CSRF_TOKEN
                        },
                        cache: RESTfulCache
                    },
                    update: {
                        method:'PUT',
                        isArray: false,
                        headers: {
                            'X-CSRF-TOKEN': app.CSRF_TOKEN
                        },
                        transformResponse: function (data, headers){
                            RESTfulCache.removeAll();
                        }
                    },
                    save : {
                        method:'POST',
                        isArray: false,
                        headers: {
                            'X-CSRF-TOKEN': app.CSRF_TOKEN
                        },
                        transformResponse: function (data, headers){
                            RESTfulCache.removeAll();
                        }
                    }
                };

                if(functionSetting){
                    for(var i in functionSetting){
                        if(typeof defaultFunction[i] == typeof {}){
                            for(var j in functionSetting[i]){
                                defaultFunction[i][j] = functionSetting[i][j];
                            }
                        }else{
                            defaultFunction[i] = functionSetting[i];
                        }
                    }
                }
                var returnRes = $resource(url, defaultParam, defaultFunction);
                returnRes.getCache = function (){
                    return RESTfulCache;
                }
                return returnRes;
            }
        });
    }
)
大家讲道理

Use route interceptor to define global header

   $httpProvider.interceptors.push(['$rootScope', '$q', function ($rootScope, $q) {

      return {
        request: function (config) {

          // Header - Token
          config.headers = config.headers || {};
          if (config.headers) {
            config.headers['ca-g-oo'] = 'data-dnwaec2ioagwqevnm';
          };
          
          return config;
        },

        response: function (response) {

          if (response.status == 200) {
            // console.log('do something...');
          }
          
          return response || $q.when(response);
        },

        responseError: function (response) {
   
          return $q.reject(response);
        }
      }
    }])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template