Search code examples
javascripthtmlangularjsmd-autocomplete

md-autocomplete don't wait data from a service. How to resolve?


I want to build a md-autocomplete, but I can not show the options. Always shows the error message that should only be launched when there are no options for the input inserted.
My service returns correctly and my controller only return after receiving service data.

HTML:

<md-autocomplete placeholder="Postal-Code"
                 md-selected-item="selectedItem" 
                 md-no-cache="true"
                 md-search-text="searchText" 
                 md-items="item in welcomeScope.getPostalCode(searchText)"
                 md-item-text="item.cp4Code">
  <md-item-template>
    <span md-highlight-text="searchText">{{item.cp4Code}}</span>
  </md-item-template>
  <md-not-found>
    ERROR
  </md-not-found>
</md-autocomplete>

Controller:

welcomeScope.getPostalCode = function (key){
   welcomeSvc.getAllPostalCodes(key).then(function(data){
   return data.result.returnvalue;
});  

Service:

var getAllPostalCodes = function(key){
        return Restangular.all(...).post(JSON.stringify()).then(function(response){
            var obj = angular.fromJson(response);
            if (!obj.isError) {
                return obj;
            }
            else{
                console.log("ERROR!");
            }
        });
};

An example result returned in controller is:

[  
  {"id":00001,"cp4Code":"1000","cp3Code":"111","postalDesignator":"aaaaa"},  
  {"id":00002,"cp4Code":"1000","cp3Code":"112","postalDesignator":"bbbbb"},  
  ...      
]

Solution

  • welcomeScope.getPostalCode has no return value, returning from inside a promise doesn't affect the outer function. Indentation makes this a bit more clearer, like this:

    welcomeScope.getPostalCode = function (key){
        welcomeSvc.getAllPostalCodes(key).then(function(data){
            return data.result.returnvalue;
        });
    };
    

    If you don't return the promise from welcomeSvc.getAllPostalCodes then md-autocomplete doesn't have any way of getting the results.

    welcomeScope.getPostalCode = function (key){
        return welcomeSvc.getAllPostalCodes(key).then(function(data){
            return data.result.returnvalue;
        });
    };