【问题标题】:How to correctly load multiple model on an ember.js view如何在 ember.js 视图上正确加载多个模型
【发布时间】:2017-12-05 23:16:37
【问题描述】:

(Ember 2.14)我有一个产品编辑路径的子视图,我想在其中显示与另一个模型(许可证)的关系。当然product hasMany licenceslicence belongsTo produit。我还有一个添加关系的组件。据我了解,我应该在路由的模型函数中从组件外部加载所有数据。

当我从 emberApp 的其他地方转到路线时,它会显示正确的关系,但是当我直接转到页面时,只有第一个许可证显示为关系。

这是 produits.edit.document 路由的模型:

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    const produit = this.modelFor('produits.edit')
    return Ember.RSVP.hash({
      allLicences: this.get('store').findAll('licence'),
      produit: produit
    });
  }
});

produits.edit 路由的模型:

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('produit', params.produit_id);
  }

licence.js:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr(),
  produits: DS.hasMany('produit'),
  licenceVersions: DS.hasMany('licence/licence-version')
});

产品型号:

import Ember from 'ember';
import DS from 'ember-data';
import { modelAction } from 'ember-custom-actions';

export default DS.Model.extend({
  nom: DS.attr(),
  resume: DS.attr(),
  description: DS.attr(),
  description_sec_title: DS.attr(),
  illustration: DS.attr(),
  isPublished: DS.attr('boolean'),
  famille: DS.belongsTo('famille'),
  licences: DS.hasMany('licence'),
  addLicence: modelAction('licences', {method: 'POST'}),
  anyLicence: Ember.computed('licences.[]', function() {
    return this.get('licenses').length > 0;
  })
});

模板的 produits.edit.documents 部分呈现来自产品的许可证。

{{#each model.produit.licences as |licence|}}
        <tr>
          <td>{{licence.name}} </td>
          <td>{{interface/remove-button deleteElement=(action "removeLicence" licence model.produit model.produit.licences)}}</td>
          <td></td>
        </tr>
{{/each}}

在这两种情况下,从应用程序访问或重新加载应用程序、ember 检索产品和许可证索引。在一种情况下,他将只显示产品的第一个许可证,在另一种情况下,他将显示与产品相关的所有正确许可证。

我在这个路由模型中做错了什么?

编辑: 现在它可以工作,如果

  • 许可证包含在来自服务器的产品(产品)JSON 响应中

  • 对 API 的 JSON 调用是代码 200 而不是 304。在这两种情况下,浏览器工具都是相同的。它仅适用于 Firefox。有时,第一个测试失败 (200),但它在第二个 (304) 工作,并且在随后的重新加载 (304) 失败

【问题讨论】:

  • 您能否也显示许可证的模型定义(尤其是定义关系的部分)以及当您直接点击该路线时后端/api 发送给您什么?
  • 以及 - 另外 - 您在哪里以及如何显示/获取许可证?在模板中,在控制器中?如何?这一切都很重要......

标签: ember.js ember-data


【解决方案1】:

您可以做的是同步加载关系。为此,您可以像这样licences: DS.hasMany('licence', { async: false }) 更改您的关系。现在,您必须在执行查询时包含关联,例如 this.store.findRecord('produit', params.produit_id, { include: 'licences' })。您可以加载更多这样的关联,{ include: 'licences.licence_versions,famille' }。更多信息请查看this

您可能还在您的关联中使用{inverse: 'licences'},如您所见here

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多