0

我使用服务来请求数据,然后将服务注入到组件中。从 Ember Mirage 中检索数据。

我的问题是我无法将数据显示为属性,即使在 computedProperty 中使用此属性时,computedProperty 也会正确计算和显示。

Emblem 中的组件模板:

.notifications-number {{notificationService.countUnread.content}}
each notificationService.notifications.content as |notification|
  span {{notification.text}}

通知服务:

import Ember from 'ember';

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

  // render bugs out
  notifications: function() {
    return this.get('store').findAll('notification')
  }.property(),

  // renders correctly
  countUnread: function() {
    return DS.PromiseObject.create({
      promise: this.get('notifications').then((notifications) => {
        return notifications.get('length')
      })
    });
  }.property(),
});

海市蜃楼配置:

this.get('/notifications', () => {
    return {
      data: [
        {id: 1, type: 'notification', text: 'hi im notification', link: ''},
        {id: 2, type: 'notification', text: 'hi im notification 2', link: 'google.com'}            
      ]
    };
  });

我对另一个服务和组件有类似的问题,其中检索到的数据不是数组而是对象。

  • {{myService.myProperty}}渲染<(subclass of Ember.ObjectProxy):ember404>
  • {{myService.myProperty.content}}渲染<my-app@model:myModel::ember580:1>
  • {{myService.myProperty.content.myModelField}}什么都不渲染。

当我在应用程序初始化时手动设置存储中的值时,一切正常,但在将实际异步请求发送到 API 模拟时不起作用。

4

1 回答 1

0

这里的问题是我的适配器的 JSON 格式不正确(我认为某些变量是连字符而不是下划线)。

但是,这不是将数据从 API 加载到服务的正确方法。现在我认为最好的方法是在 routes/application.js model() 钩子中加载数据并将其推送到 setupController() 中的服务。这是它现在的样子:

  // routes/application.js

  model() {
      return Ember.RSVP.hash({
        user: this.get('store').queryRecord('user', {}),
        notifications: this.get('store').findAll('notification', { reload: true })
      })
  },

  setupController(controller, model) {
    this._super(...arguments)

    if (model)
      this.set('notificationService.notifications', model.notifications.sortBy('createdAt').reverse())
  },

在服务中,它可以在没有任何承诺的情况下使用,依赖于计算属性:

  // services/notificationService.js

  countUnread: function() {
    let notifications = this.get('notifications')
    if (notifications)
      return notifications.filterBy('read', false).get('length')
  }.property('notifications')

当然不需要.content在任何控制器或模板中使用。

于 2017-02-24T06:55:13.570 回答