Ember-在 application.js 中加载的数据模型在 ember-simple-auth 身份验证后未加载

Ember-data models that load in application.js not loaded after ember-simple-auth authentication

我目前正在加载一些 ember-数据,这些数据在 routes/application.js 路由的站点范围内使用。然后可以在任何地方访问该数据。特别是,数据从 templates/application.hbs 模板传递到组件,并且 store.peekAll() 从其他各种地方访问。

无论这种方法是否正确(我欢迎对此提出反馈!),这对我有用,但以下情况除外:

如果用户未通过身份验证,我无法查询数据,因为他们尚未获得查看数据的授权。这是我的代码:

// routes/application.js
import Ember from 'ember';

export default Ember.Route.extend(ApplicationRouteMixin, {
  model() {
    if (this.get('session.isAuthenticated')) {
      return Ember.RSVP.hash({
        clients: this.store.findAll('client', {include: 'projects'}),
        resources: this.store.findAll('resource')
      });
    }
  }
});

我想在他们验证后加载数据,但我不知道如何重新加载模型。如果我只是在sessionAuthenticated hook中加载数据,如下:

// routes/application.js
sessionAuthenticated() {
  this.controller.set('clients', this.store.findAll('client', {include: 'projects'}));
  this._super(...arguments);
}

没用。 store 被数据填充,但依赖于此数据的组件永远看不到它。另外,我过渡到下一个的路线,也取决于数据,由于同步性没有及时。

一定有一种简单的方法可以做到这一点,但我对它是什么感到困惑。观察员?强制 routes/application.js model() 方法重新 运行(并等待承诺 returns)现在 session.isAuthenticatedtrue?

ember: 2.5.x, ember-数据: 2.5.x

试试这个:

// routes/application.js
import Ember from 'ember';

export default Ember.Route.extend(ApplicationRouteMixin, {
  model() {
    if (this.get('session.isAuthenticated')) {
      return Ember.RSVP.hash({
        clients: this.store.findAll('client', {include: 'projects'}),
        resources: this.store.findAll('resource')
      });
    }
    return {};
  },
  sessionAuthenticated() {
    this.store.findAll('client', {include: 'projects'}).then(clients => {
      this.controller.set('model.clients', clients);
    });

    this._super(...arguments);
  }
});

我实现的服务如下:

// services/lime-core.js
import Ember from 'ember';

export default Ember.Service.extend({
  store: Ember.inject.service(),
  resources: null,
  clients: null,

  init() {
    this.set('resources', []);
    this.set('clients', []);

    this.get('store').findAll('resource').then(resources => {
      this.set('resources', resources);
    });
    this.get('store').findAll('client', {include: 'projects'}).then(clients => {
      this.set('clients', clients);
    });
  }
});

然后我可以访问模板中的 limeCore 服务,前提是它已被注入:

// components/foo/component.js
export Ember.Component.extend({
  limeCore: Ember.Service.inject(),
  ...
}

和我的模板:

// components/foo/template.hbs
<ul>
  {{#each limeCore.resources as |resource|}}
    <li>{{resource.name}}</li>
  {{/each}}
</ul>