我的控制器中有这个代码(我在视图中执行了ng-repeat):
$scope.projects = Restangular.all('projects').getList().$object;
然后我将此对象从mongolab API返回
[
{
_id: { "$oid" : "546a3bdee4b0bfd97138fe08"},
"picture" : "http://placehold.it/400x400" ,
"name" : "Square Campus" ,
"address" : "293 Grafton Street, Shasta, Arizona, 6757" ,
"phone" : "+1 (916) 544-2274" ,
"buildings" : [
{ "name" : "North Campus" , "floors" : "4" , "users" : "8"} ,
{ "name" : "South Campus" , "floors" : "2" , "users" : "15"} ,
{ "name" : "East Wing" , "floors" : "8" , "users" : "23"}
]
},
{
... // Other project
},
{
... // Other project
}
]
现在,这本身就可以正常工作,我可以在视图中显示数据。但我尝试添加RequestInterceptor和ResponseInterceptor以在加载数据时添加加载微调器。
添加此内容:
RestangularProvider.addRequestInterceptor(function () {
console.log('loading data');
});
RestangularProvider.addResponseInterceptor(function () {
console.log('loaded data');
});
导致以下错误:
Error: Response for getList SHOULD be an array and not an object or something else
当我尝试访问建筑物时,我在详细信息页面中遇到了类似的问题:
var detailProject = Restangular.one('projects', $routeParams.projectId);
detailProject.get().then(function (project) {
$scope.project = project;
project.buildingTotals = _.reduce(project.buildings,
function (sums, building) {
return {
floors: sums.floors + parseInt(building.floors),
};
},
{ floors: 0 }
);
});
API返回:
{
"_id" : { "$oid" : "546a3bdee4b0bfd97138fe08"} ,
"picture" : "http://placehold.it/400x400" ,
"name" : "Square Campus" ,
"address" : "293 Grafton Street, Shasta, Arizona, 6757" ,
"phone" : "+1 (916) 544-2274" ,
"buildings" : [
{ "name" : "North Campus" , "floors" : "4" , "users" : "8"} ,
{ "name" : "South Campus" , "floors" : "2" , "users" : "15"} ,
{ "name" : "East Wing" , "floors" : "8" , "users" : "23"}
]
}
给出以下错误:
TypeError: Cannot read property 'buildings' of undefined
请注意,如果ConfigurationInterceptor中没有ResponseInterceptor,则不会发生这种情况。
我做错了吗?我想我是否指定每个返回应该是一个对象?
答案 0 :(得分:3)
您必须从拦截器返回值。
var pendingRequests = 0;
RestangularProvider.addRequestInterceptor(
function (element, operation, what, url) {
if (pendingRequests == 0) {
console.log('loading data (show indicator)');
}
pendingRequests++;
return element;
});
RestangularProvider.addResponseInterceptor(
function (data, operation, what, url, response, deferred) {
pendingRequests--;
if (pendingRequests == 0) {
console.log('loaded data (hide indicator)');
}
return data;
});
RestangularProvider.addErrorInterceptor(
function(response, deferred, responseHandler) {
pendingRequests--;
if (pendingRequests == 0) {
console.log('loaded data (hide indicator)');
}
return true; // error not handled
});
有关详细信息,请参阅文档: