TypeError:无法读取未定义的属性.then

时间:2017-07-11 18:33:59

标签: javascript angularjs promise

我接受输入并在每个项目的描述中查找。服务中的控制台语句显示所需的输出,但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');
            });
        };
    }

}) ();

1 个答案:

答案 0 :(得分:3)

您永远不会从函数getMatchedMenuItems返回创建的承诺,因此调用promise.then(function (result)将失败。在getMatchedMenuItems中更改此行

var response = $http({...

return $http({...

解决方案是在整个堆栈中使用promises。让该服务函数返回承诺并让控制器调用then,以便在解决承诺后它可以正常工作。

我很想将此标记为How do I return the response from an asynchronous call?的副本。我建议至少阅读它,这可以让你更好地了解如何使用promises。

相关问题