2017-07-11 14 views
0

各項目の説明で入力して調べます。サービス内のconsoleステートメントは望ましい出力を示しますが、ctrlの約束はエラーが発生した場所です。私は何が欠けていますか?TypeError:プロパティの読み込みが未定義

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

インデントは恐ろしいです...あなたは1つ以上の閉じ括弧と括弧を開いたものよりも持っています。 – trincot

答えて

3

あなたはとてもpromise.then(function (result)は失敗します呼び出して関数getMatchedMenuItemsから作成した約束を返すことはありません。

var response = $http({... 

return $http({... 

に対する解決策は、スタック全体を通じて約束で動作するようです

から getMatchedMenuItemsにこの行を変更します。そのサービス機能が約束を返して、コントローラーに thenと呼ぶようにして、約束が解決されたら仕事をすることができます。


私はHow do I return the response from an asynchronous call?の重複としてこれをマークするように誘惑しています。私はそれを読むことをお勧めします。これは、あなたが約束をどのように働かせるかについてのよりよい考えを与えるはずです。

+1

要するに、OPは 'service.getMatchedMenuItems'の' $ http'約束を返すのを忘れました。 – Icycool

+0

@Icycool - 'found 'という変数を返すので' Forgot'を使用することを躊躇しています。彼らは約束をどのように働かせるか分からない。 – Igor

+0

@lcycoolまた、 'MenuSearchService'には戻り値がありません。 – trincot

関連する問題