我接受输入并在每个项目的描述中查找它。服务中的控制台语句显示了所需的输出,但 ctrl 中的 promise 是发生错误的地方。我错过了什么?
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');
});
};
}
}) ();
最佳答案
你永远不会从你的函数返回创建的 promise getMatchedMenuItems
如此称呼promise.then(function (result)
将失败。更改 getMatchedMenuItems
中的这一行来自
var response = $http({...
到
return $http({...
解决方案是在整个堆栈中使用 Promise。让该服务函数返回 promise 并让 Controller 调用 then
因此,一旦 promise 得到解决,它就可以发挥作用。
我很想将其标记为 How do I return the response from an asynchronous call? 的重复项。我建议您至少通读一遍,这应该能让您更好地了解如何使用 Promise。
关于javascript - TypeError : cannot read property . 然后是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45042188/