How to Instantiate a Service and Only Inject It Into A Single Route


#1

I don’t think I’m fully understanding the dependency injection. I have a service that I’d like to instantiate and have it injected into a single route and single controller. The codepen below has the full code inside it.

Ember.Application.initializer({
  name: 'alert-service-initializer',
  initialize: function(container, application){
    application.register('service:alert-service', application.AlerterService, { singleton: true });
    // application.inject('route', 'Alerter', 'service:alert-service');
  }
});

App.AlerterService = Ember.Service.extend({
   name: "AlerterService",
   yellWhenReady: function() {
     alert('hey!');
   }.on('init')
});

App.IndexRoute = Ember.Route.extend({
  alertService: Ember.inject.service('alert-service'),
  model: function() {
    return ['red', 'yellow', 'blue'];
  }
});

The code above will not alert “hey”. However if I uncomment out the application.inject line, it will display. What’s going on here? What am I missing?


#2

Services are lazily generated…meaning, they’re not instantiated until they’re actually needed. So, if you try to get the service in your model hook, that’ll do what you want.

App.IndexRoute = Ember.Route.extend({
alertService: Ember.inject.service('alert-service'),
  model: function() {
    this.get('alertService');
    return ['red', 'yellow', 'blue'];
  }
});