AngularJS - 使用jQuery param格式化资源GET动词查询字符串

时间:2012-12-30 19:09:23

标签: angularjs angular-resource

我有一个后端,它以jQuery的$.param格式返回了解查询字符串。例如,有一个像

这样的对象
{ search: "Miller", name: ["Felipe", "Fernanda"] }

将使用以下查询字符串请求URL:

http://theurl/path?search=Miller&name%5B%5D=Felipe&name%5B%5D=Fernanda 

基本上它使用name[]=Felipe&name[]=Fernada,但是使用了URL编码。

当AngularJS解析时,同一个对象最终会使用以下格式:

http://theurl/path?search=Miller&name=Felipe,Fernanda

我的后端不明白。

阅读this other question,我认为使用transformRequest会有所帮助,但事实并非如此。这是我的测试代码:

HTML

<div ng-controller="UserCtrl">
    <pre>{{ data | json}}</pre>
</div>

的JavaScript

var myApp = angular.module('myApp',['ngResource']);

var transformFn = function(data, headersGetter) {
    console.debug('transformRequest', data);
    if (!data) return;
    console.debug('data in', data);
    var dataOut = $.param(data);
    console.debug('data out', dataOut);
    return dataOut;
};

myApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.transformRequest.push(transformFn);
}]);

myApp.factory('User', ['$resource', function($resource) {
    return $resource('/echo/:type/', {type:'json'}, {
        query: { method: 'GET' }
    });
}]);

myApp.controller('UserCtrl', ['$scope', 'User', function($scope, User) {
    User.query({ seach: 'Miller', name: ['Felipe', 'Fernanda']}, 
       function(data) {
           console.debug('data', data);
           $scope.data = data;
       });
}]);

但是,当您尝试运行此代码时,您会注意到transformFn上的数据属性始终未定义,并且查询字符串保持AngularJS格式。

你也可以在jsFiddle中看到这个:http://jsfiddle.net/fcoury/QKmnX/

知道如何强制查询字符串使用jQuery的$ .param格式吗?

编辑:我正在检查分支v1.0.x的AngularJS代码,我找不到任何方法来更改查询字符串构造代码,这是在这里发生的:

https://github.com/angular/angular.js/blob/v1.0.x/src/ngResource/resource.js#L299-L306

有没有人有任何聪明的方法来覆盖ngResource类的那部分?

2 个答案:

答案 0 :(得分:1)

我的简单解决方案:

module.run(['$http', '$httpParamSerializerJQLike', function($http, $httpParamSerializerJQLike) {
  $http.defaults.paramSerializer = $httpParamSerializerJQLike;
}]);

答案 1 :(得分:0)

你为什么要使用推? here中的示例只是分配:

$httpProvider.defaults.transformRequest = function(data) {...};