4

如何创建工厂 $resource 或 $http 服务来处理来自外部资源的具有多个任意参数的查询字符串?例如。

#/animals
#/animals?gender=m
#/animals?color=black
#/animals?size=small
#/animals?gender=m&color=black
#/animals?size=med&gender=f
#/animals?size=lg&gender=m&color=red

这个想法是,用户可以按下按钮/输入将其添加到查询字符串中的当前参数列表中,以获取具有不同组合的所需属性的新动物列表。我已经尝试了以下方法,但它没有根据需要重新加载或向现有 url 添加新参数。另外,我不确定是否应该在控制器或工厂中调用 $route.current.params 以及这是否是最好的方法。

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', $route.current.params, { query: {method: 'GET', isArray: true}});
}]);

谢谢 :)

4

1 回答 1

10

如果调用资源时传入的参数与 url 中指定的任何占位符都不匹配,它们会自动转换为查询字符串参数。因此,您应该执行以下操作:

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', { query: {method: 'GET', isArray: true}});
}]);

然后当你尝试使用它时,你可以这样做:

Animals.query({size:"med",gender:'f'});

它会被翻译成:

http://thezoo.com/animals?size=med&gender=f
于 2013-08-27T20:54:13.923 回答