Restangular:getList con objeto que contiene una matriz incrustada
-
21-12-2019 - |
Pregunta
En mi proyecto AngularJS, estoy intentando usar el método getList de Restangular pero devuelve un error porque la respuesta de la API no es directamente una matriz sino un objeto que contiene una matriz.
{
"body": [
// array elements here
],
"paging": null,
"error": null
}
El mensaje de error de Restangular es:
Error: Response for getList SHOULD be an array and not an object or something else
¿Es posible decirle a Restangular que la matriz que está buscando está dentro del body
¿propiedad?
Solución
Sí, mira el Documentación rectangular.Puedes configurar Restangular así:
rc.setResponseExtractor(function(response, operation) {
if (operation === 'getList') {
var newResponse = response.body;
newResponse.paging = response.paging;
newResponse.error = response.error;
return newResponse;
}
return response;
});
Editar:Parece que la API de Restangular ahora ha cambiado, para mejor, y que el método actual a utilizar es agregarRespuestaInterceptor.Es posible que se necesiten algunos ajustes en la función pasada.
Otros consejos
Creo que deberías usar un GET personalizado del Métodos personalizados
Restangular.all("url").customGET(""); // GET /url and handle the response as an Object
como collin allen sugerido que puedes usar agregarRespuestaInterceptor como esto:
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;
});
});