在访问商店的服务上计算 属性

Computed property on a service that accesses the store

我写了一个加载通知的服务:

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
    });
  }
});

我想在有未读通知时更改导航栏中图标的颜色。导航栏是一个组件:

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;
    });
  })
});

然后模板使用 hasUnreadNotifications 属性 来决定是否应该使用高亮 class:

<span class="icon">
  <i class="fa fa-bell {{if hasUnreadNotifications 'has-notifications'}}"></i>
</span>

但是,它不起作用。虽然商店被调用并且通知被 returned,hadUnreadNotifications 没有解析为布尔值。我认为这是因为它 return 是一个承诺,而模板无法处理它,但我不确定。

问题

从计算 属性 返回承诺将不起作用。计算属性不是 Promise 感知的。要使其正常工作,您需要 return DS.PrmoiseObject 或 DS.PromiseArray.

您可以阅读此 igniter article 提供的其他选项。

import Ember from 'ember';
import DS from 'ember-data';

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

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

});