【发布时间】:2017-12-15 23:12:47
【问题描述】:
我接受输入并在每个项目的描述中查找。服务中的控制台语句显示了所需的输出,但 ctrl 中的承诺是错误发生的地方。我错过了什么?
NarrowItDownController.$inject=['MenuSearchService'];
function NarrowItDownController(MenuSearchService) {
var ctrl = this;
ctrl.searchTerm = "";
ctrl.found=[];
ctrl.searchlist = function () {
if (ctrl.searchTerm.length > 0) {
console.log(ctrl.searchTerm);
var promise = MenuSearchService.getMatchedMenuItems(ctrl.searchTerm);
promise.then(function (result) {
ctrl.found = result;
}).catch(function (error) {
console.log("something went wrong!!!");
});
}
};
}
MenuSearchService.$inject = ['$http'];
function MenuSearchService($http) {
var service= this;
var found = [];
service.getMatchedMenuItems = function (searchTerm) {
var response = $http({
method: "GET",
url: ("https://davids-restaurant.herokuapp.com/menu_items.json")
}).then(function (response) {
for (var i = 0; i < response.data.menu_items.length; i++) {
if (response.data.menu_items[i]
.description.toLowerCase().indexOf(searchTerm)>-1 ) {
found.push(response.data.menu_items[i]);
}
}
console.log(found);
return found;
}, function() {
console.log('error');
});
};
}
}) ();
【问题讨论】:
-
缩进太可怕了……你的右大括号和圆括号比左大括号多一个。
标签: javascript angularjs promise