javascript - TypeError : cannot read property . 然后是未定义的

标签 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');
            });
        };
    }

}) ();

最佳答案

你永远不会从你的函数返回创建的 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/

相关文章:

Javascript: indexOf($(this) 获取点击元素的数组索引值?

javascript - ui-grid (AngularJS) ColumnDefs 中名称和字段之间的区别?

JavaScript promise : conventional way to pass arguments

angularjs - Angular js 指令中的后链接与预链接

angularjs - 如何从 $stateChangeStart 访问 UI-Router 根状态的 'resolve' 属性?

javascript - 在延迟对象解析后执行 Thenable 函数

javascript - 将 Promise 返回给没有 $$state 的变量

javascript - 将类添加到特定的同级元素,而不是页面上出现的每个同级元素

javascript - 是否可以在图表 js 中使用 mouseenter 和 mouseleave 事件?

javascript - 在 Vue.js 中将组件属性传递给组件的惯用方法是什么?