为什么 angular $resource 查询并期望来自同一个 URL 的不同响应?

Why does angular $resource query and get expect different responses from the same URL?

我问这个是因为它让我觉得我不能以 'angular' 的方式做某事,因为我的代码不必要地复杂。

我已经定义了一个资源

Question = $resource("/questions/:id", {id: "@id"});

现在如果我这样做

Question.get(1);

它将转到 /questions/1 并期待一个对象作为响应 如果我这样做

Question.query({id: 1});

它将转到 /questions/1 但期望一个数组作为响应

我明白为什么这样做是因为 isArray 默认设置。

我有客户端代码,但我不知道它将查询多少个 ID。 我可以通过让我的 angular 代码执行

轻松解决这个问题
if (ids.length == 1)
  Question.get(ids);
else
  Question.query({id: ids})

并让我的服务器在数组长度为 1 时发送一个对象,但这似乎过于复杂,让我觉得我一定是在以错误的方式处理这个问题。

是否有更清洁的解决方案?

不确定这是否是 angular 方式,但我找到的解决方案稍微干净一些,是在我的查询中使用不同的参数,以便它命中 rails 上的索引方法的显示,所以总是可以安全地 return 一个数组。

像这样:

Question = $resource("/questions/:id", {id: "@id"});

q = Question.get(1);
// Performs GET /questions/1
// q = { id: 1, ...};

q = Question.query({ids: 1});
// Performs GET /questions?ids=1
// q = [{id: 1, ... }];

q = Question.query({ids: [1,2]});
// Performs GET /questions?ids=1&ids=2
// q = [{id: 1, ... }, {id: 2, ...}];