在我的addRequestInterceptor函数中,我想确保获得正确的响应结构,否则会生成错误。
例如,我希望服务器对getList的响应是response.data.items,例如{ data: items: [...] }
(根据google style guide)
所以我希望请求拦截器函数在结构无效时生成错误(而不是返回undefined等)。
答案 0 :(得分:0)
查看Restangular文档以进行配置。
https://github.com/mgonto/restangular#addresponseinterceptor
app.config(function(RestangularProvider) {
// add a response intereceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
//Done if the getList operation type is made so that you don't do the same for a single get
if(operation === 'getList'){
//Checks if items is undefined and if it is an array
if(!angular.isUndefined(data.items) && angular.isArray(data.items)){
deferred.resolve(data.items);
} else {
deferred.reject({error: 'Malformed Response. That is not right!'});
}
} else {
//Just continue and resolve the data on other operations
//Add whatever else you want for handling responses
deferred.resolve(data);
}
});
然后,您可以在请求资源上的.then()中处理请求的错误函数的错误。