在我的AngularJS项目中,我正在尝试使用Restangular getList方法,但它返回错误,因为API响应不是直接数组而是包含数组的对象。
{
"body": [
// array elements here
],
"paging": null,
"error": null
}
Restangular错误消息是:
Error: Response for getList SHOULD be an array and not an object or something else
是否有可能告诉Restangular它正在寻找的数组是否在body
属性中?
答案 0 :(得分:22)
是的,请参阅Restangular documentation。您可以像这样配置Restangular:
rc.setResponseExtractor(function(response, operation) {
if (operation === 'getList') {
var newResponse = response.body;
newResponse.paging = response.paging;
newResponse.error = response.error;
return newResponse;
}
return response;
});
编辑:似乎Restangular的API现在已经改变了,并且当前使用的方法是 addResponseInterceptor 。传递的函数可能需要进行一些调整。
答案 1 :(得分:19)
我认为您应该使用Custom Methods
中的customGET Restangular.all("url").customGET(""); // GET /url and handle the response as an Object
答案 2 :(得分:6)
如Collin Allen建议你可以像这样使用addResponseInterceptor:
app.config(function(RestangularProvider) {
// add a response intereceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === "getList") {
// .. and handle the data and meta data
extractedData = data.body;
extractedData.error = data.error;
extractedData.paging = data.paging;
} else {
extractedData = data.data;
}
return extractedData;
});
});