How to initialize the Ember service when loading the application without type input?

It may be a little esoteric, but I need help.

My use case is a clock. I want a service that will init()start a timer after . (e.g. AJAX polling service). I want this to start by loading the application, but I don't want to inject it into every type of object.

What I tried:

  • Writing a service and using it Ember.inject.service()in an application controller.
  • Use an initializer with app.register(…, MyService.create(), {instantiate: false})no call app.inject(…).
  • Do not start the timer in init()place of Ember.inject.service()it in the route / application controller and in your call init() this.get('myService').startTimer().

Here are some of the stumbling blocks that I have encountered:

  • Services are lazy loading, so the timer never starts because the application controller never executed this.get('myService'). I could do it in the controller init(), but it was like the smell of code.
  • It seems that ember resolver will see the file services/my-service.jsand automatically register it. Execution app.register()seems to register two instances, and two are confused.
  • Like getting a lazy service in an application controller init(), this solution also felt like a code smell. But of all the solutions I tried, this works and is the least smelly of the three.

Are there any other alternatives?

+4
source share
1 answer

TL DR Use Instance Initializer

, .

init(), , , Embers . - .

- , - , Ember 1.13 2.0:

// app/instance-initializers/start-my-service.js
export function initalize(app) {
  const { container = app } = app;
  const myService = container.lookup('service:my-service');
  myService.startPolling();
}

export default {
  initialize,
  name: 'start-my-service'
};

ember-twiddle.

+8

All Articles