user3125823
user3125823

Reputation: 1900

Why am I getting TypeError on length property

Getting this error:

TypeError: Cannot read property 'length' of undefined

For this code:

var getSuggestions = function(query) {
searchService.getSuggestions(query).then(function(es_return){
  var suggestions = es_return.suggest.phraseSuggestion;
  var results = es_return.hits.hits;

  if (suggestions.length > 0) {
    $scope.autocomplete.suggestions = suggestions;
  }
  else {
    $scope.autocomplete.suggestions = [];
  }

  if (results.length > 0) {
    $scope.autocomplete.results = results;
  }
  else {
    $scope.autocomplete.results = [];
  }

  if (suggestions.length > 0 || results.length > 0) {
    $scope.showAutocomplete = true;
  }
  else {
    $scope.showAutocomplete = false; 
  }
});

};

Specifically on the first if statement and I don't see why? Need some fresh eyes to show me what I'm doing wrong.

Upvotes: 1

Views: 46

Answers (4)

user3125823
user3125823

Reputation: 1900

After I drilled down on this more, I noticed that I had an issue with the ES query that I was using for the ac code. It was actually just a typo. Where I had phrasesuggestion in the js, I had phrase_suggestion in the json query for ES, once I fixed that - it worked! Thanks for your efforts.

Upvotes: 0

qzenchik
qzenchik

Reputation: 46

Try to debug the code from the developer console.

Probably you should es_return.hits.hits remake to es_return.hits.

In your case es_return.hits.hits or suggestions are not an array.

Upvotes: 0

Jim VanPetten
Jim VanPetten

Reputation: 436

I think you need some better null handling. With Suggestion.length > 0 null cannot be evaluated with >, right? So probably use boolean instead (or both).

if (Suggestion.length){
   //do stuff
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

It looks like your es_return.suggest.phraseSuggestion is undefined.You can try like this:

if(suggestions != undefined)
{
if (suggestions.length > 0) {
    $scope.autocomplete.suggestions = suggestions;
  }
  else {
    $scope.autocomplete.suggestions = [];
  }
}

Upvotes: 0

Related Questions