我在http://localhost:4200/products呈现product
表,其中应包含每个产品的category
,但不包括。{/ p>
模板代码:
应用/模板/产品/ index.hbs
[...]
<tbody>
{{#each product in model}}
<tr>
<td>
{{product.name}}
</td>
<td>
{{product.category.name}}
</td>
[...]
为什么{{product.category.name}}
没有显示product.name
?我该如何解决?模拟错了吗?
ember new shop
cd shop
ember install:addon ember-cli-scaffold
ember g scaffold product name:string
ember g scaffold category name:string
ember g adapter application
ember g http-mock products
ember g http-mock categories
应用/适配器/ application.js中
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
'namespace': 'api'
});
应用/模型/ product.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
category: DS.belongsTo('category', { async: true })
});
应用/模型/ category.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
products: DS.hasMany('product')
});
服务器/嘲笑/ products.js
module.exports = function(app) {
var express = require('express');
var productsRouter = express.Router();
productsRouter.get('/', function(req, res) {
res.send({
'products': [
{"id":1,"name":"Orange","category":1},
{"id":2,"name":"Banana","category":1},
{"id":3,"name":"Potato","category":2}
]
});
});
[...]
服务器/嘲笑/ categories.js
module.exports = function(app) {
var express = require('express');
var categoriesRouter = express.Router();
categoriesRouter.get('/', function(req, res) {
res.send({
'categories': [
{"id":1,"name":"Fruits","products:":[1,2]},
{"id":2,"name":"Vegetables","products:":[3]}
]
});
});
[...]
答案 0 :(得分:1)
您应该将belongsTo
定义为异步:
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
category: DS.belongsTo('category', { async: true })
});
这将为您访问的每个类别执行GET请求。
或者你可以用产品来装载它们。
看看这个jsbin,它表明它可以正常工作。
如果你看看你的模拟服务器,你会看到这条路线:
categoriesRouter.get('/:id', function(req, res) {
res.send({
'categories': {
id: req.params.id
}
});
});
正如您在请求category
1时所看到的那样,它将返回一个只有该ID的对象。
因此,添加{ async: true }
会根据category
向/category/1
发出请求(当它是类别1时)。你必须确保你返回正确的对象。
例如:
var categoryList = [
{"id":1,"name":"Fruits","products:":[1,2]},
{"id":2,"name":"Vegetables","products:":[3]}
]
categoriesRouter.get('/:id', function(req, res) {
res.send({
'categories': categoryList.filter(function(c) {
return c.id == req.params.id;
})[0]
});
});