模型中带有belongsTo的计算属性返回未定义

Fab*_*bic 1 javascript handlebars.js ember.js

我有3个模型。

// Product
export default DS.Model.extend({
    content: DS.attr('string'),
    creator: DS.belongsTo('user')
});

// User
export default DS.Model.extend({
    email: DS.attr('string'),
    products: DS.hasMany('product'),
    person: DS.belongsTo('person'),
    fullName: Ember.computed(function() {
        return `${this.get('person.firstname')} ${this.get('person.surname')}`;
    })
});

// Person
export default DS.Model.extend({
    firstname: DS.attr('string'),
    surname: DS.attr('string'),
    users: DS.hasMany('user')
});
Run Code Online (Sandbox Code Playgroud)

我尝试在车把上使用它。

{{#each products as |product|}}
    {{product.creator.fullName}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

如您所见,User模型中有一个计算属性。但是它总是返回,undefined undefined因为this.get('person.firstname')this.get('person.surname')返回undefined。

灰烬检查器显示每个模型的数据。任何想法如何解决这个问题?

小智 5

默认情况下,关系是异步的,并返回promise。这意味着您在查询数据时就没有数据。当您第一次询问数据时,它将被加载,并且您需要在计算的属性中添加相关键以fullNamePerson模型解析时得到更新。

PS。您可以看一下如何ember-promise-helpers在模板中组织异步数据的插件。

// User
export default DS.Model.extend({
    email: DS.attr('string'),
    products: DS.hasMany('product'),
    person: DS.belongsTo('person'),

    fullName: Ember.computed('person.{firstname,surname}', function() {
        return `${this.get('person.firstname')} ${this.get('person.surname')}`;
    })
});

// Person
export default DS.Model.extend({
    firstname: DS.attr('string'),
    surname: DS.attr('string'),
    users: DS.hasMany('user')
});
Run Code Online (Sandbox Code Playgroud)