I'm trying to get two get 2 lists of blog posts from 2 categories (news and events), then display them in 2 different columns of my home page. It is required for me to perform 2 separate Ajax calls to get those blog posts. I do not use ember-data for this operation, as I don't see the advantage of using it in this scenario (but I may be wrong).
export default Ember.Route.extend({
setupController(controller, model) {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }).then(function (data) {
controller.set('news', data.posts);
});
Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' }).then(function (data) {
controller.set('events', data.posts);
});
}
});
The above code works. But from what I read in the Ember documetation, I should be getting those data in the model
hook (instead of setupController
) to take advantage of promises. So I tried to re-write my code this way:
export default Ember.Route.extend({
model() {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
return {
news: function () {
return Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }).then(function (data) {
return data.posts;
})
},
events: function () {
return Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' }).then(function (data) {
return data.posts;
})
}
};
}
});
But this does not work. The Ajax calls are done but too late, after the page has rendered. I'm not sure here what I'm doing wrong. Would there be any advantage of using ember-data for that scenario?
Function ajax can only make one Ajax call. A callback function is executed when the Ajax call is successful.
Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.
You return an object containing two promises, rather than an actual promise. What you need is to build your own promise (Ember.RSVP.Promise) that will be resolved once both of the inner promises resolves.
You can return an hash of Promises with RSVP.hash()
You could do this:
export default Ember.Route.extend({
model() {
var wpUrl = 'http://public-api.wordpress.com/rest/v1/sites/company.wordpress.com/posts/?number=2&category=';
return new Ember.RSVP.hash({
news: Ember.$.ajax({ url: wpUrl + 'news', dataType: "jsonp", type: 'GET' }),
events: Ember.$.ajax({ url: wpUrl + 'events', dataType: "jsonp", type: 'GET' })
});
}
});
Read more about promises in Ember here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With