Accessing sideloaded data in route and template

I’m tinkering with how to load related product and category data in the same request (using RESTAPI not JSONAPI…sorry!). I am able to perform the sideloading just fine, but for some reason I can’t access my side-loaded data in ‘setupController’ using ‘model.products’ (or ‘model.data.products’). But I can access it just fine in the template using ‘model.products’. Why would that be? I can see both ‘category’ and ‘product’ models in the ember inspector and they have the requisite data.

When I try this in setupController:

setupController(controller, model) {
	controller.set('results', model.products);
}

I get:

TypeError: Cannot read property '_relationships' of undefined

I’m also noticing that my “main” (not sideloaded) category data is available in setupController, but I have to prefix the fields with model.data.[field]. I’m unsure as to why the ‘data’ is required.

Some dumbed-down test data representing my json is:

{
	"category": {
		"categoryName": "test category",
		"id": 6,
		"products": [
			4419,
			502,
			3992
		]
	},
	"products": [{
		"description": "Whatevs",
		"id": 4419,
		"name": "Product 1",
		"price": 114.95,
		"skuid": "S21046"
	}, {
		"description": "Whatevs",
		"id": 502,
		"name": "Product 2",
		"price": 114.95,
		"skuid": "SOLS2594"
	}, {
		"description": "Whatevs",
		"id": 3992,
		"name": "Product 3",
		"price": 114.95,
		"skuid": "S21015"
	}]
}

category model:

export default DS.Model.extend({
	products: hasMany('product'),
	categoryName: attr('string')
});

product model:

export default DS.Model.extend({

	name: attr('string'),
	skuid: attr('string'),
	price: attr('number'),
	description: attr('string')

});

route model hook:

	model(params) {
		let category = this.get('store').queryRecord('category', {
			id: params.id
		}).catch(function(ex) {
		    console.log('parsing failed', ex);
		});
		return category;
	}

In the JavaScript of Ember apps, you need to use get/set to manipulate Ember.Objects. Try model.get('products'), but remember that relationships are asynchronous by default in Ember Data 2.x, so you might want to do model.get('products').then(p => controller.set('results', p)); instead.

Or just refer to model.products in the template and skip setupController mucking.

Makes sense - thanks locks!

1 Like