一尘不染

如何为自定义Angular $ resource操作指定标头参数

angularjs

以下工作正常,但是我认为这会全局修改$ httpProvider,这不是我想要的。

angular.module('SessionService', ['ngResource'])
    .config(function($httpProvider){
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    })
    .factory('Login', function($resource){
        var resource = $resource('/adminui/login',{},{
            post:{
                method:"POST",
                isArray:false
            },
        });
        return resource;
    })
LoginCtrl = function($scope,Login) {
    $scope.login = function(){
        Login.post($.param({user:$scope.user.username,password:$scope.user.password}),$.noop,$.noop)
    }
}

反正有这样做吗?

...
    .factory('Login', function($resource){
        var resource = $resource('/adminui/login',{},{
            post:{
                method:"POST",
                isArray:false,
                headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'} // ignored
            },
        });
        return resource;
    })

“标题”参数似乎被忽略了。请求仍然

Content-Type:application/json;charset=UTF-8

我的标头值可以吗?


阅读 197

收藏
2020-07-04

共1个答案

一尘不染

我已经确认1.1.3确实支持这一点。但是,您需要确保您还获得了资源服务的1.1.3版本。快速测试:

angular.module('myApp', ['ngResource']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {templateUrl: 'partials/partial1.html',controller: 'MyController'});
    $routeProvider.otherwise({redirectTo: '/'});
  }])

  .controller("MyController", function( $scope, Bug) {
    Bug.post({test:"test"});
  })

  .factory('Bug', function($resource){
    var resource = $resource('/bug',{},{
        post:{
            method:"POST",
            isArray:false,
            headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'} 
        },
    });
    return resource;
});

这将发出一个标头设置为(使用Chrome确认)的请求:

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

快速说明,我无法找到angular-
resource.js的下载,因此我不得不去github网站下载它。这是在这里

For some giggles, I created a fiddle. Notice that there will be a failed POST
call, but its headers are set correctly. Example
Fiddle

2020-07-04