我正在使用 Angular 服务从 API 获取详细信息,并且我只想返回匹配的项目。这意味着,在输入一些文本后,我将单击一个按钮,该按钮将调用 Controller 中的一个函数,该函数将调用服务来获取详细信息。
现在我的问题是,它返回整个列表而不是过滤后的列表,我已将过滤结果存储到一个数组中,我想返回该数组(foundItems)。
这是我的代码
(function() {
angular.module('NarrowItDownApp',[])
.constant('url',"https://davids-restaurant.herokuapp.com/menu_items.json")
.controller('NarrowItDownController',['$scope','MenuSearchService',function($scope,MenuSearchService) {
var items=this;
items.searchitem="";
items.getitems=function() {
MenuSearchService.getMatchedMenuItems(items.searchitem).then(function(response) {
this.found=response.data;
console.log(this.found);
})
.catch(function(response) {
this.found=response.data;
console.log(this.found);
});
};
}])
.service('MenuSearchService',['$http','url',function($http,url) {
var service=this;
service.getMatchedMenuItems=function(searchitem)
{
var foundItems=[];
var key;
return $http.get(url).success(function(data) {
for(var i=0;i<data.menu_items.length;i++)
{
var temp=data.menu_items[i];
//Old method
/*for(key in temp)
{
if(temp.hasOwnProperty(key))
{
console.log(temp[key])
}
}*/
Object.keys(temp).forEach(function(items)
{
if(searchitem==temp[items])
{
foundItems.push(temp);
}
});
};
console.log(foundItems);
return foundItems;
})
.error(function(data) {
console.log('error');
return data;
});
return foundItems;
};
}]);
})();
最佳答案
Now my problem, is that it returns the entire list not the filtered list, I have stored filter result into an array I want to return that array(foundItems).
服务返回整个列表的原因是 .success
和 .error
方法ignore 返回值。请改用 .then
和 .catch
。
service.getMatchedMenuItems=function(searchitem)
{
var foundItems=[];
var key;
//return $http.get(url).success(function(data) {
//USE .then method
return $http.get(url).then(function(response) {
var data = response.data;
for(var i=0;i<data.menu_items.length;i++)
{
var temp=data.menu_items[i];
Object.keys(temp).forEach(function(items)
{
if(searchitem==temp[items])
{
foundItems.push(temp);
}
});
};
console.log(foundItems);
return foundItems;
})
//.error(function(data) {
//USE .catch method
.catch(function(errorResponse) {
console.log(errorResponse.status);
//return data;
//THROW to chain rejection
throw errorResponse;
});
//return foundItems;
};
使用 throw statement 也很重要在拒绝处理程序中。否则,被拒绝的 promise 将转换为成功的 promise 。
有关详细信息,请参阅Angular execution order with $q
.
关于javascript - Angular 服务不过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43211744/