如何使用 Ember CLI 在 Ember 中进行依赖注入?

2023-12-21

首先,我制作了一个没有 Ember CLI 的小型 Ember 应用程序。

我有这段代码。

window.MyApp = Ember.Application.create({
  ready: function() {
    this.register('session:current', MyApp.SessionController, { singleton: true });
    this.inject('controller', 'session', 'session:current');
  }
});

这奏效了。

然后我决定用 Ember CLI 从头开始​​重写一切。

我编辑了文件app/app.js并添加了ready就像我之前的版本一样。

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver,
  ready: function() {
    this.register('session:current', App.SessionController, { singleton: true });
    this.inject('controller', 'session', 'session:current');
  }
});

这是行不通的。

会话控制器确实存在。这就是文件的内容app/controllers/session.js

export default Ember.Controller.extend({
  isLoggedIn: false,
});

我收到的错误消息是

TypeError: Attempting to register an unknown factory: `session:current`

它出现在浏览器中。

我用 google 搜索了该消息,但在 Ember CLI 中没有找到任何有关依赖注入的信息。

任何想法?


在 ember-cli 中你可以使用ember generate service <name of service> and ember generate initializer <name of initializer>构建存根来实现这一点,这比摆弄要好得多app.js.

您创建一个服务基本上是这样的:

// app/services/notifications.js
import Ember from 'ember';

export default Ember.Object.extend({
  initNotifications: function() {
     // setup comes here
  }.on('init'),

  // Implementation snipped, not relevant to the answer.
});

以及初始化程序,它将服务注入到需要它的应用程序的组件中:

// app/initializers/notifications-service.js
import Notifications from '../services/notifications';

export default {
  name: 'notification-service',
  after: 'auth-service',

  initialize: function( container, app ) {
    app.register( 'notifications:main', Notifications, { singleton: true } );
    app.inject( 'component:system-notifications', 'notificationService', 'service:notifications' );
    app.inject( 'service:auth', 'notificationService', 'service:notifications' );
  }
};

这样,它就可以作为notificationService在指定的组件上。

有关 Ember 中依赖注入主题的文档可以在以下位置找到:http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/ http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Ember CLI 在 Ember 中进行依赖注入? 的相关文章

随机推荐