Hi,
I have a router (eg products) where I want to determine dynamically, based on the response of the json api, whether to display a listing of categories or items.
In my router I have a property
isCategories:false
and in the model hook something like this, where I want to be able to change the isCategories property depending on the value returned from the api call - true/false
model() {
Ember.$.post('/api/products/showCategoriesOrItems').then(function(answer) {
// I can't use this.set('isCategories',true) for example
});
}
What I then want to do is return the model depending upon the revised value of isCategories so something like
if (this,get('isCategories')) {
return this.store.findAll('product-category');
}
else {
return this.store.findAll('product')
}
Any help much appreciated!
Use a “fat arrow” function to keep this
context;
model() {
Ember.$.post('/api/products/showCategoriesOrItems').then( answer => {
this.set('isCategories',true);
});
}
Hi,
Many thanks for getting back - sorry should have done that.
However, still not getting the result I need eg
isCategories:false;
model() {
Ember.$.post('/api/products/showCategoriesOrItems').then(answer => {
console.log(answer.data.categories); // true;
this.set('isCategories',answer.data.categories);
});
console.log(this.get('isCategories')); // false
}
Hope that helps
That’s because console.log(this.get('isCategories')); // false
runs while the Ember.$.post()
is happening (not after). I think you just want to embed your category logic within the .then()
callback.
model() {
return Ember.$.post('/api/products/showCategoriesOrItems').then( answer => {
if ( answer.data.categories ) {
return this.store.findAll('product-category');
} else {
return this.store.findAll('product');
}
});
}
In addition, I’d suggest using the ember-ajax
addon for requests rather than jQuery’s version.
// within your route js file
ajax: Ember.inject.service(),
model() {
return this.get('ajax').post('/api/products/showCategoriesOrItems').then( answer => {
if ( answer.data.categories ) {
return this.store.findAll('product-category');
} else {
return this.store.findAll('product');
}
});
}
Hi
That’s brilliant many thanks - I had tried returning the models directly but the plugin definitely helps - many thanks for helping out here.