【问题标题】:Ember.js: getting model relationships from component's javascriptEmber.js:从组件的 javascript 中获取模型关系
【发布时间】:2017-08-15 21:54:17
【问题描述】:

我正在构建一个组件,我注意到一种对我来说似乎很奇怪的行为。我的组件调用如下:

{{my-component model=model}}

我的模型包含如下关系:

type: DS.belongsTo('type')

现在,在my-component.js 中,如果我登录到控制台this.get('model.type.name')(或this.get('model').get('type').get('name')),我会得到undefined。但是,如果在my-component.hbs中插入{{model.type.name}},则值显示正确。

我不太了解这种行为:如何像在组件的 Handlebars 模板中一样从组件的 javascript 中访问模型的关系?

谢谢!

【问题讨论】:

    标签: javascript ember.js handlebars.js ember-components


    【解决方案1】:

    在 ember-data 中,关系被视为 Promise,因此您应该使用 then 作为结果。

    this.get('model').get('type').then((result) =>{
     console.log(' Name ', result.get('name'));
    });
    

    参考: https://guides.emberjs.com/v2.14.0/models/relationships/#toc_relationships-as-promises

    【讨论】:

    • 感谢您的反馈,但是,如果我尝试执行this.get('model').then(model => { console.log(model) }),我会收到TypeError: this.get(...).then is not a function。我不明白为什么会这样:/
    • 不过,您的代码 sn-p 确实有效,所以我想知道为什么 this.get('model').then 不是函数...
    • belongsTohasMany 等关系将返回 Promise。这里modelmodel 挂钩的解析模型无关。你可以做then只是为了承诺
    • 是的,非常有意义。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2014-03-04
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多