【问题标题】:AngularJS - How to set transformParams for query stringAngularJS - 如何为查询字符串设置 transformParams
【发布时间】:2014-04-11 09:46:57
【问题描述】:

我正在尝试使用以下代码正确编码 angular 上的查询参数:

getAccount = function (accountEmail, accountCreationDate) {

      var data = {
        accountEmail: accountEmail,
        accountCreationDate: accountCreationDate
      };

      return $http.get('/administration/account.json', {params: $filter('noBlankValues')(data)}).then(
        function (result) {
          $log.debug('getAccount result: ' + JSON.stringify(result.data));
          return result.data.result;
        }
      );
    };

accountCreationDate 是一个 ISO-8601 字符串(例如“2014-03-20T14:56:01.691+01:00”)。根据http://docs.angularjs.org/api/ng/service/$http,我将参数作为对象传递,但在框架中我有以下“奇怪”的查询输出:

?accountCreationDate=2014-03-20T14:56:01.691%2B01:00&accountEmail=test@test.com

即日期“+”已编码,但对象的其余部分未编码。您知道出了什么问题以及如何解决吗?

PS:我知道我可以手动编写编码的查询字符串,但我正在寻找一个更用户友好的解决方案。

【问题讨论】:

  • 输出是指用于发出请求的 url,对吗?你期望什么输出?
  • 对,我希望:?accountCreationDate=2014-03-20T14%3A56%3A01.691%2B01%3A00&accountEmail=test%40test.com

标签: javascript angularjs httprequest


【解决方案1】:

好的,通过使用以下变换函数解决了这个问题:

var transform = function () {
      headers: {
        'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      transformRequest: function (obj) {
        var str = [];
        for (var p in obj) {
          if ((typeof obj[p] !== 'undefined') &&
            (typeof obj[p] !== 'function')) {

            if (obj[p] instanceof Date) {
              str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p].toISOString()));
            }
            else if (obj[p] instanceof Array) {
              for (var i in obj[p]) {
                if (obj[p][i] instanceof Object) {
                  str.push(encodeURIComponent(p) + '=' + encodeURIComponent(JSON.stringify(obj[p][i])));
                } else {
                  str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p][i]));
                }
              }
            }
            else if (obj[p] instanceof Object) {
              str.push(encodeURIComponent(p) + '=' + encodeURIComponent(JSON.stringify(obj[p])));
            }
            else {
              str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
            }
          }
        }
        return str.join('&');
      }
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多