简体   繁体   中英

Ember - findAll and promises

I have a little problem using findAll in my component. It concerns the value it returns at the end.

users: Ember.computed(function() {
return this.get('store').findAll('user');
}),

In my case, I want to get the name of the first object. So in my handlebar:

users.firstObject.name

'users' is a class in this case. But I'm trying to return directly the first object in the property, like this:

user: Ember.computed(function() {
    return this.get('store').findAll('user')
    .then(function(user){
      return user.get('firstObject');
    });
  }),

But in this case, in my handlebar, user.name is undefined and user is a promise. There is something I can't understand with promises, how they work ... Can somebody help me to get the correct user without using 'firstObject' on my users ? Thanks in advance !

The shortest way to solve your problem is to install an ember-promise-helpers addon and apply it in your template as follows:

{{#if (await user)}}
  {{get (await user) 'name'}}
{{/if}}

However, AFAIK, it is not recommended to use promises as values for computed properties, although you can still do it. here I would recommend the documentation for Ember.PromiseProxyMixin as well as reading some (although older) forum threads (for instance this one ).

I think the problem you're having is not with the promises, but how you're using the computed property.

The best place for a findRecord/findAll is in a model hook in the route. It is best to not rely on firstObject for what you're describing. You have no guarantees about which record will be first as your app's back end data changes.

Computed properties are really meant for watching other data and updating the displayed information about that data, not for fetching things from the store on their own. They require arguments that are the names of the data they are supposed to be watching for updates. Since your computed property isn't watching anything, it never fires. Here's an example.

  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    let firstName = this.get('firstName');
    let lastName = this.get('lastName');

    return `${firstName} ${lastName}`;
  })

You can read more under Computed Properties in the Guides.

You will have a much easier time if you define a model hook in a route that gets the user's info using findRecord and then passes it to child components or sets it on a service if many different components on different routes need the user information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM