Angularjs 重写$http post以使用附加数据扩展每个post数据

Angularjs 重写$http post以使用附加数据扩展每个post数据,angularjs,http-post,Angularjs,Http Post,在Yii框架中,我们必须向POST数据添加CSRF令牌,以便验证请求 令牌是由PHP生成的,我像这样传递变量 angular.module('MyConstant', []).constant("MyConstant", {'postdata': {'_csrf': 'ABCDEF'}}); //this is written by PHP var app = angular.module('MyApp', ['MyConstant']); app.controller('MyC

在Yii框架中,我们必须向POST数据添加CSRF令牌,以便验证请求

令牌是由PHP生成的,我像这样传递变量

angular.module('MyConstant', []).constant("MyConstant", 
     {'postdata': {'_csrf': 'ABCDEF'}}); //this is written by PHP

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

app.controller('MyCtrl', [
    '$scope', '$http', 'MyConstant',
    function ($scope, $http, MyConstant) {
}]);
 {"_csrf": "ABCDEF", "data": "bla bla bla"}
每当我想发邮件的时候,我都得做这样的事情

  $http.post(url, angular.extend(MyConstant.postdata, {data: mydata}));
邮政机构将是这样的东西

angular.module('MyConstant', []).constant("MyConstant", 
     {'postdata': {'_csrf': 'ABCDEF'}}); //this is written by PHP

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

app.controller('MyCtrl', [
    '$scope', '$http', 'MyConstant',
    function ($scope, $http, MyConstant) {
}]);
 {"_csrf": "ABCDEF", "data": "bla bla bla"}
我只是好奇是否有一种“角度方法”来覆盖
$http.post
,以自动附加数据以避免像上面的
Angular.extend(viewstants.postdata
那样的代码重复

更新

感谢@GregL提供的指针。我可以使用
拦截器这样做

app.config(['$httpProvider', 'MyConstant', 
    function ($httpProvider, MyConstant) {
    $httpProvider.interceptors.push(function () {
        return {
            request: function (config) {
                if (config.method == "POST"){
                    config.data = angular.extend(MyConstant.postdata, config.data);
                }
                return config;
            }
        };
    });
}]);

是的,您应该能够注册一个


只需为
请求
方法添加一个拦截器,并检查
config.method===“POST”
,如果是,将常量添加到发送的数据中(
config.data
).

它可以工作。我刚刚使用您建议的
拦截器添加了完整的工作代码。非常感谢!如果您不想修改
MyConstant.postdata
,您应该使用空对象作为
angular.extend()
config.data=angular.extend({},MyConstant.postdata,config.data)的第一个参数;
。这在中提到。