显示产品的 belongsTo 类别

Display belongsTo category for a product

我在 http://localhost:4200/products 渲染了一个 product table,其中应该包括每个产品的 category 但没有。

模板代码:

app/templates/products/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

app/adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});

app/models/product.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  category: DS.belongsTo('category', { async: true })
});

app/models/category.js

import DS from 'ember-data';

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

server/mocks/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}
        ]
      });
  });
  [...]

server/mocks/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]}
        ]
      });
  });
  [...]

您应该将 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 时看到的那样,它将 return 一个仅具有该 ID 的对象。

因此,添加 { async: true } 会根据 category/category/1 执行一个请求(当然,当它是类别 1 时)。您必须确保 return 对象正确。

例如:

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]
  });
});