2014-06-06 21 views
0

我需要一種方法來添加默認數據屬性的http請求
我想是這樣的

var app = angular.module('dumbhttp', []); 

app.service('dumbhttp', function ($http, $location) { 
    this.post = function(url, data){ 
     data.prePopData = 'sameInfoForEveryRequest'; 
     return $http.post(url, data); 
    }; 
}); 

這個工作,但它似乎並不像正確的做事方式。
我必須使用angulars的服務dumbhttp $ http

如果這工作,它將是偉大的!

var app = angular.module('$http', []); 

app.service('$http', function ($http, $location) { 
    this.post = function(url, data){ 
     data.prePopData = 'sameInfoForEveryRequest'; 
     return $http.post(url, data); 
    }; 
}); 

,但可惜它沒有:-(

也許這樣的事情可能是做正確的方式這

$http.setDefaluts.requestData.mykey = 'mydefaultvalue' 

林REST方式不使用這只是擡起頭,出隊隊使用不同的架構

在此先感謝!
-James

回答

2

您需要使用攔截器:

$httpProvider.interceptors.push(function($q, dependency1, dependency2) { 
    return { 
    'request': function(config) { 
     config.data.prePopData = 'sameInfoForEveryRequest'; 
     return config; 
     } 
    }; 
    }); 
+1

是的,你需要使用攔截器。更多信息(和澄清)可以在這裏找到(https://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/)。 – earthmeLon

+0

這就是即時尋找,但它不是很有效的權利。當我做'''config.data.prePopData ='sameInfoForEveryRequest';'''它說數據是未定義的,所以我定義數據,它的工作原理,但是我的數據,我傳遞給$ http會丟失.. –

+0

'TypeError :無法設置屬性'prePopData'undefined''' –