dimanche 12 février 2017

Computed property on a service that accesses the store

I wrote a service for loading notifications:

import Ember from 'ember';

export default Ember.Service.extend({
  sessionUser: Ember.inject.service(),
  store: Ember.inject.service(),

  read() {
    let currentUserId = this.get('sessionUser.user.id');
    return this.get('store').query('notification', {
      userId: currentUserId,
      read: true
    });
  },

  unread() {
    let currentUserId = this.get('sessionUser.user.id');
    return this.get('store').query('notification', {
      userId: currentUserId,
      read: false
    });
  }
});

I want to change the colour of an icon in the navigation bar when there are unread notifications. The navigation bar is a component:

import Ember from 'ember';

export default Ember.Component.extend({
  notifications: Ember.inject.service(),
  session: Ember.inject.service(),

  hasUnreadNotifications: Ember.computed('notifications', function() {
    return this.get('notifications').unread().then((unread) => {
      return unread.get('length') > 0;
    });
  })
});

And the template then uses the hasUnreadNotifications property to decide if the highlight class should be used:

<span class="icon">
  <i class="fa fa-bell "></i>
</span>


However, it doesn't work. Although the store is called and notifications are returned, the hadUnreadNotifications doesn't resolve to a boolean. I think this is because it returns a promise and the template can't deal with that, but I'm not sure.

Questions

  • Is it idiosyncratic ember to wrap the store in a service like this. I'm doing this because it feels clumsy to load the notifications in the application route just to show the count.
  • Why doesn't hasUnreadNotifications return a boolean?
  • Is it possible to make read and unread properties instead of functions, so a computed property can be created in the service to calculate the count?

Aucun commentaire:

Enregistrer un commentaire