Ember 在路由中注入时服务未定义

Ember service undefined when injected in route

当我在路由中注入服务并尝试将其访问到模型中,甚至在 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}} 但只有当我在组件中执行此操作时它才有效。

为了从控制器访问 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}}