I am trying to display the user who is currently logged in.
Few things to note. user
has an async
relationship with profile
. In the user
model, I have:
profile: DS.belongsTo('polymorphable', { polymorphic: true, async: true }),
My application route has:
model() {
return this.store.findRecord('user', this.currentSession.get('id'));
},
The application template has something like:
<div class="profile-photo">
{{image-tag imageUrl=model.profile.imageUrl}}
</div>
The image-tag
component object has a computed property:
src: Ember.computed('imageUrl', {
get() {
let imageUrl = this.get('imageUrl');
console.log(imageUrl.indexOf('imgix') > -1) // returns error
}
})
I get Uncaught TypeError: Cannot read property 'indexOf' of undefined
. This happens because model.profile
returns a promise and is still resolving by the time the template is rendered.
This is how I got it working. I created an afterModel
hook:
afterModel: function(model, transition) {
model.get('profile').then(profile => {
this.controller.set('profile', profile);
});
},
Then in application template I, instead, have:
<div class="profile-photo">
{{#if profile}}
{{image-tag imageUrl=profile.imageUrl size="mini" class="-small -round"}}
{{/if}}
</div>
Which tells Ember to wait for profile
to be resolved from the promise.
Does this look "dirty"? Perfectly fine? Or should I consider an alternative approach?
Actually, all you need is
afterModel: function(model, transition) {
return model.get('profile');
}
Following that, you can access model.profile
as usual. See the question marked as possible duplicate for more information.