Pergunta

I've got a controller that has a searchQuery and suggestions property. The suggestions come from an AJAX request. How can I make the suggestions property a promise in my Controller?

app/controllers/application.js

import Ember from 'ember';

const { computed, $ } = Ember;

export default Ember.Controller.extend({
  searchQuery: '',
  suggestions: computed('searchQuery', function() {
    return $.getJSON(`songs/search.json?q=${this.get('searchQuery')}`);
  })
});
Foi útil?

Solução

I assume you mean, how can I get the results from the promise, since you are returning a promise to the suggestions property.

searchQuery: '',

suggestions: [],

suggestionsUpdater: Ember.observer('searchQuery', function(){
  var self = this;
  Ember.$.getJSON('songs/search.json?q=' + this.get('searchQuery')).then(function(data){
    self.set('suggestions', data);
  });
})

There are only a few places where you can return/send a promise and ember's going to assume you didn't want to store the promise. The model hook, and transitionTo/transitionToRoute methods. The rest of the time they leave it up to you, in case you actually wanted to keep track of the promise.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top