imnothardcore imnothardcore - 1 month ago 12
Javascript Question

using ember trying to set value in controller from route model hook yields error

I have a controller for this route that I have created and everything else in the controller seems to work great. I am trying to pass the meta value to a variable in the controller from the route and I get a console error:

Error: Property set failed: object in path "controller" could not be found or was destroyed.


this is the relevant snippet in my route:

model(params){
let someVariable = this.store.query('somePath', params);
someVariable.then((results) => {
this.set('controller.totalPages', results.get('meta.page_count'))
});
return someVariable;
}


in the console error the line with the issue is this one

this.set('controller.totalPages', results.get('meta.page_count'));


The other interesting snippet is when I sort a row on my data table and make the model request again my 'totalPages' variable finally shows up as expected(with the meta value), its on the initial page load that I dont see it.

Answer

When the model hook is executed, controller has not been set up yet. Check out the route lifecycle--the controller is available after model and afterModel etc. have not only returned but also the promises they return have resolved. You should move your logic into setupController.

model(params) {
    return this.store.query('somePath', params);
},

setupController(controller, model) {
    controller.set('totalPages', model.get('meta.page_count'));
    this._super(...arguments);
}

Or, you could skip the setupController and just put an alias in your controller:

totalPages: Ember.computed.alias('model.meta.page_count')