【问题标题】:Restangular: Not passing parameter if emptyRestangular:如果为空,则不传递参数
【发布时间】:2015-05-25 15:04:34
【问题描述】:

我在使用 RestAngular 的 AngularJS 应用程序中有以下控制器方法:

    $scope.findFriend = function (name, type, limit) {
        return FriendSearch.getList({
            name: name,
            type: type,
            limit: limit
        });
    };

可能是 typeempty(没有内容的字符串,长度 = 0) - Restangular 生成以下无效 URL:

http://host:port/rest/friends/search?limit=10&name=Peter&type=

正确的做法是省略它:

http://host:port/rest/friends/search?limit=10&name=Peter

当然,我可以在传递之前检查参数。但我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • 我认为这可能会帮助你ng-newsletter.com/posts/restangular.html'使用requestInterceptors'。从文档“我们可以处理要发送到服务器的数据”中,您可以查看对象并删除空字段
  • 谢谢。我会检查这个。
  • @yuyokk 不幸的是,它不起作用。据我所知,不存在任何元素,并且给出的 url 没有参数。

标签: javascript angularjs parameters restangular


【解决方案1】:

很遗憾,我无法使用 Restangular 1.4 版重现此问题。我创建了一个类似于您的示例的小提琴:

http://plnkr.co/edit/ovwd8wUhBkhPXtBNDfbw?p=preview

摘录:

  // http://run.plnkr.co/search?name=foo
  $scope.findFriend('foo');
  // http://run.plnkr.co/search?name=foo&type=bar
  $scope.findFriend('foo', 'bar');
  // http://run.plnkr.co/search?limit=3&name=foo
  $scope.findFriend('foo', null, '3');
    // http://run.plnkr.co/search?limit=3&name=foo
  $scope.findFriend('foo', undefined, '3');

作为参数给出的nullundefined 都按预期工作。 这意味着我们需要更多信息/代码,因为该行为可能是由其他原因引起的。

对于空字符串,最简洁的方法是简单地检查''并替换为null。

我相应地更新了小提琴:

  $scope.findFriend = function (name, type, limit) {
    return FriendSearch.getList({
      name: name === '' ? null : name,
      type: type === '' ? null : type,
      limit: limit === '' ? null : limit
    });
  };
  // http://run.plnkr.co/search?limit=3&name=foo
  $scope.findFriend('foo', '', '3');

【讨论】:

  • 感谢您的评价。我们使用的版本是一样的。在我的描述中,我所说的 empty 是指一个空字符串。我将更新描述以澄清这一点。
猜你喜欢
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多