在路线注入时,Ember服务未定义

时间:2018-04-13 13:24:39

标签: ember.js service ember-data

当我在路由中注入服务并尝试将其访问到模型中或甚至在beforeModel中时,服务未定义,但是当我尝试访问服务的值时,一切都是未定义的。

我的服务看起来像这样

import Service from '@ember/service';
import { inject as service } from '@ember/service';
import RSVP from 'rsvp';

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

  load() {
    if (this.get('session.isAuthenticated')) {
      return this.get('store').queryRecord('user', { me: true }).then((user) => {
        this.set('user', user);
      });
    } else {
      return RSVP.resolve();
    }
  }
});

我的路线

import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import RSVP from 'rsvp';

import { inject as service } from '@ember/service';

export default Route.extend(AuthenticatedRouteMixin, {
  session: service('session'),
  currentUser: service('currentUser'),

});

我想在我的模板中访问它,例如{{currentUser.user.email}},但它只在我在组件中执行此操作时才有效。

1 个答案:

答案 0 :(得分:2)

要从控制器访问currentUser服务,请将服务注入控制器。路由需要首先调用currentUser.load方法,以便填充服务上的user属性。请注意,您可能只想调用currentUser.load方法一次,因此我建议您在应用程序路径中执行此操作。

<强> route.js

import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import RSVP from 'rsvp';

import { inject as service } from '@ember/service';

export default Route.extend(AuthenticatedRouteMixin, {
  session: service('session'),
  currentUser: service('currentUser'),
  model() {
    // This will load the user data before rendering
    // This can also be done in the beforeModel
    return this.get('currentUser').load();
  }
});

<强> controller.js

import Controller from '@ember/controller';
import { inject as service } from '@ember/service;

export default Controller.extend({
    currentUser: service()
});

template.hbs

Email: {{currentUser.user.email}}