javascriptember.jshandlebars.jsember-components

Ember.js: getting model relationships from component's javascript


I am building a component, and I have noticed a behaviour that seems very odd to me. My component is invoked as follows:

{{my-component model=model}}

My model contains a relationship as follows:

type: DS.belongsTo('type')

Now, in my-component.js, if I log to console this.get('model.type.name') (or this.get('model').get('type').get('name')), I get undefined. However, if in my-component.hbs I insert {{model.type.name}}, the value is displayed correctly.

I don't really understand this behaviour: how can I access a model's relationship from within a component's javascript just like I do in the component's Handlebars template?

Thanks!


Solution

  • In ember-data, relationship is treated as Promise so you should use then for the result.

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

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