【问题标题】:TypeError: cannot read property .then of undefined [duplicate]TypeError:无法读取未定义的属性.then [重复]
【发布时间】: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


【解决方案1】:

你永远不会从你的函数 getMatchedMenuItems 返回创建的 Promise,所以调用 promise.then(function (result) 会失败。将getMatchedMenuItems 中的这一行从

var response = $http({...

return $http({...

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


我很想将其标记为How do I return the response from an asynchronous call? 的副本。我建议至少通读一遍,这应该能让你更好地了解如何使用 Promise。

【讨论】:

  • 简而言之,OP忘记在service.getMatchedMenuItems中返回$httppromise
  • @Icycool - 在这种情况下,我犹豫是否使用 forgot,因为他们正在返回一个名为 found 的变量,所以看起来这是故意的,他们不确定如何使用 Promise。跨度>
  • @lcycool,同样MenuSearchService 缺少返回值。
  • 我现在看到了,在我看来他们好像在退回一些东西,但事实并非如此,由于可怕的缩进,它对我来说只是这样。
  • 刚刚修复了缩进...
猜你喜欢
  • 2019-08-19
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2014-11-29
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多