【问题标题】:Computed property on a service that accesses the store访问商店的服务上的计算属性
【发布时间】:2017-02-12 19:58:10
【问题描述】:

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

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 属性来决定是否应该使用高亮类:

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

但是,它不起作用。尽管调用了 store 并返回了通知,但 hadUnreadNotifications 不会解析为布尔值。我认为这是因为它返回了一个承诺,而模板无法处理它,但我不确定。

问题

  • 将商店包装在这样的服务中是不是很奇怪。我这样做是因为在应用程序路由中加载通知只是为了显示计数感觉很笨拙。
  • 为什么hasUnreadNotifications 不返回布尔值?
  • 是否可以使用readunread 属性代替函数,以便在服务中创建计算属性来计算计数?

【问题讨论】:

    标签: ember.js promise ember-data


    【解决方案1】:

    从计算属性返回承诺将不起作用。计算属性不是 Promise 感知的。要使其正常工作,您需要返回 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;
                })
            });
        })
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多