Search code examples
javascriptajaxember.jsember-cliember-addon

ember-select-2 issue while using type-ahead with Ajax Queries


I'm using ember-select-2 as a typeahead in ember application.the problem is i can fetch the data from the server but the data isn't showing in dropdown.any help would be appreciated.Thanks in advance.

 {{select-2
    placeholder="Choose from our many pizzas"
    value=chosenTypeaheadPizza
    typeaheadSearchingText="Searching pizzas"
    typeaheadNoMatchesText="No pizzas found for '%@'"
    typeaheadErrorText="Loading failed: %@"
    query="queryPizzas"
 }}

and action handler is

queryPizzas(query) {    
        var self = this;
        var store = self.get('store');
        let adapter = store.adapterFor("pizzas"); 
        let serachQuery = query.term;      
           adapter.searchPizza(serachQuery).then(function(response) {

                console.log(response.pizzas);

           }); 
    },

Response

    {
    "pizzas": [{
        "id": 1,
        "name": "pizza 1"
    }, {
        "id": 2,
        "name": "pizza 2"
    }]
   }

Solution

  • If you check the examples of ember-select-2; you can see that it is using deferred parameter passed to action handler to display the data. It says there "Make sure to not call query.callback directly but always use the provided deferred!". This means, you need to call deferred that is to be provided as the second argument to the action handler. I am not expert at ember-select-2 but what you should do is probably

    queryPizzas(query, deferred) {    
        var self = this;
        var store = self.get('store');
        let adapter = store.adapterFor("pizzas"); 
        let searchQuery = query.term;      
        adapter.searchPizza(searchQuery).then(function(data) {
          //try to pass the array as the data
          deferred.resolve({data: data.pizzas, more: false});
        }, deferred.reject);
    }
    

    Provided solution above works for the data format you have provided. Please check the corresponding twiddle. In this example; I have used a mock promise to simulate server remote call and returned the example data you have provided as the content to be displayed in select. You have to use optionLabelPath in order to display name of pizzas in the select as can be seen in application.hbs.