2017-04-21 49 views
0

我有3個模型。帶有belongsTo的模型中的計算屬性返回undefined

// 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') 
}); 

我嘗試在句柄中使用它。

{{#each products as |product|}} 
    {{product.creator.fullName}} 
{{/each}} 

正如你可以看到有在User模型計算的屬性。但它總是返回undefined undefined,因爲this.get('person.firstname')this.get('person.surname')返回未定義。

Ember檢查器顯示每個模型的數據。任何想法如何解決這個問題?

+0

似乎你想'人名'fullName',而不是'用戶'?不是你的問題,但... –

+0

事實上,這會導致相同的錯誤。 – Fabic

回答

3

默認情況下,關係是異步的,並返回promises。這意味着您在提問時沒有數據。當你第一次詢問數據時,它將被加載,並且你需要添加相關鍵到你的computed property得到更新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') 
}); 
+0

TIL「依賴鍵」...謝謝 –

+0

謝謝你的作品。 – Fabic