我想在每個請求中都會提交一個header,類似于 a: bbb 這樣的內(nèi)容.
// 無論是獲取列表
$scope.books = myRes.query();
// 還是單獨(dú)的一個項(xiàng)目
$scope.oneBook = myRes.get({id:2});
能在所有的RESTful這樣的請求中加入一個header,header的內(nèi)容是
ca-g-oo: data-dnwaec2ioagwqevnm
嘗試了各種方式都無法實(shí)現(xiàn)
$resource(url, [paramDefaults], [actions]);
url是設(shè)置請求的地址
paramDefaults是預(yù)設(shè)的要提交的數(shù)據(jù)
action是自定義的函數(shù)方法
感覺可以通過action來設(shè)置,但是不行
// 如果把a(bǔ)ction設(shè)置成這樣
$resource(
'ca/book/:id',
{},
{
query: {
header: {
"ca-g-oo": "data-dnwaec2ioagwqevnm"
}
},
get: {
header: {
"ca-g-oo": "data-dnwaec2ioagwqevnm"
}
}
}
);
就報(bào)錯了
Error: [$resource:badcfg] http://errors.angularjs.org/1.2.29/$resource/badcfg?p0=object&p1=array
問題也解決了。。在設(shè)置$resource的時候要設(shè)置isArray屬性
'amd';
/**
*
* RESTful創(chuàng)建服務(wù)
* by chenxuan 20160325
*
* 創(chuàng)建一個$resource對象
* query : 獲取列表
* get : 獲取單個數(shù)據(jù)
* updata : 更新數(shù)據(jù)
* save : 新建數(shù)據(jù)保存
*
* 關(guān)于緩存
* 默認(rèn)緩存query和get請求,當(dāng)有updata和save請求產(chǎn)生的時候清空所有緩存
*
* ====v1.1====20160328
* functionSetting參數(shù)的對象不會直接覆蓋沒有在對象中存在的默認(rèn)屬性
*
*/
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;
}
});
}
)
使用路由攔截器,定義全局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);
}
}
}])