我使用Angular Service從API中獲取細節,我只想返回匹配項。意思是,在我鍵入一些文本後,我將點擊一個按鈕,這將調用控制器中的一個函數,該函數將調用服務以獲取詳細信息。Angular Service不過濾數據
現在我的問題是,它返回整個列表而不是過濾列表,我已經將過濾結果存儲到一個數組中,我想返回該數組(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;
};
}]);
})();
本身並不是答案,但如果是我,我會下載整個json並將其公開在控制器中。從此,可以使用html中的簡單過濾器完成搜索。認爲這會留下更好的用戶體驗,因爲它只需要一個異步http請求。 – cYrixmorten
請參閱[爲什麼不推薦使用角度$ http成功/錯誤方法?從v1.6中刪除?](http://stackoverflow.com/a/35331339/5535245)。 '.success'和'.error'方法**忽略**返回值。 – georgeawg