ember 属性在视图中不可用,只有 ID

ember attributes not available in view, only ID

不用说,Ember 的新手,只是想完成概念验证。已经在 EmberCLI 方面得到了一些帮助,但这对我来说是个新奇事。

/routes/index.js

export default Ember.Route.extend({
  model() {
   return this.store.findAll('skill');
}});

/models/skill.js

import Model from 'ember-data/model';

export default Model.extend({
  name: DS.attr('string'),
  desc: DS.attr('string'),
  type: DS.attr('string')
});

/adapters/application.js

import DS from "ember-data";
export default DS.JSONAPIAdapter.extend({
  namespace: 'v1',
  host: 'http://edu-api.app:8000',
});

/serializers/application.js

import DS from "ember-data";
export default DS.JSONAPISerializer.extend({});

/templates/index.hbs

    <h2>Skills</h2>
    <ul>
      {{#each model as |item|}}
    <li>
    <div>
      <li>{{item}} {{item.id}} {{item.type}} {{item.name}} {{item.desc}}</li>
    </div>
    </li>
    {{/each}}
    </ul>

似乎 id 属性可用且正确,但所有其他属性都没有从 json 加载。如果我 copy/paste json 并在模型中手动设置它,它会按预期工作,那么当来自模型存储或序列化程序时是否正在进行一些过滤?

JSONAPISerializerJSONAPIAdapter 不是 简单的 JSON/REST 后端,而是完全 JSONAPI 兼容的后端。

你说当你复制粘贴并在模型上设置它时它会起作用,所以你的意思可能是这样的:

this.store.createRecord('skill', {
    id: '1',
    name: 'foo',
    desc: 'bar',
    type: 'baz'
});

这确实适用于模型创建,但不是 JSONAPI 兼容的响应!在 JSONAPI 中你会有这样的东西(如果请求应该 return 多个实体:

{
    data: [{
        id: '1',
        attributes: {
            name: 'foo',
            desc: 'bar',
            type: 'baz'
        }
    }]
}

现在你有两个选择:

  1. 使您的 API JSONAPI 兼容,或者
  2. 使用不同的适配器和序列化器。

RESTSerializer/RESTAdapter 是一个简单的默认实现,可以处理这样的结构:

{
    id: '1',
    name: 'foo',
    desc: 'bar',
    type: 'baz'
}

而且它们是高度可定制的。

查看 official API 文档。