How to do dependency injection in Ember with Ember CLI?

江枫思渺然 提交于 2019-12-13 14:33:11

问题


First, I made a small Ember app without Ember CLI.

I had this piece of code.

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

This worked.

Then I decided to rewrite everything from scratch with Ember CLI.

I edited the file app/app.js and added the ready hook just like in my previous version.

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');
  }
});

This doesn't work.

The session controller does exist. That's the content of the file app/controllers/session.js

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

The error message I get is

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

It appears in the browser.

I googled that message, but I found nothing about dependency injection in Ember CLI.

Any idea?


回答1:


In ember-cli you can use ember generate service <name of service> and ember generate initializer <name of initializer> to build the stubs to achieve this, which is far better than fiddling about with app.js.

You create a service basically like this:

// 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.
});

And the initializer, which injects the service into the component(s) of your application which need it:

// 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' );
  }
};

With that, it becomes available as notificationService on the components specified.

Documentation on the subject of dependency injection in Ember can be found at http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/



来源:https://stackoverflow.com/questions/27932790/how-to-do-dependency-injection-in-ember-with-ember-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!