Taztingo
Taztingo

Reputation: 1945

Ember start service after Store loads data

I have a service to read from a store. I created a basic initializer to findAll data to populate a store, and then after I start the service. The service happens to use the store, but no data is in the store when the service accesses it. If I manually call the function in the service after the application has loaded I'm able to get the value. I'm assuming this is because findAll's callback is put on the event queue, and I'm running the service before the event queue removes that storage population event. If this is the case how can I tell Ember to start the service once the Store has been populated?

First Initializer (I have made it so this runs first, with 'before')

export function initialize(application) {
  let store = application.__container__.lookup('service:store');
  store.findAll('my-data');
}

Second initializer

export function initialize(application) {
  let fSociety = application.__container__.lookup('service:service-FSociety');
  fSociety.start();
}

I also attempted to work with the run loop, but it didn't seem to work.

export function initialize(application) {
  let fSociety = application.__container__.lookup('service:service-FSociety');
  Ember.run.scheduleOnce('afterRender', this, function() {
    fSociety.start();
  }

}

Upvotes: 0

Views: 180

Answers (1)

locks
locks

Reputation: 6577

The short answer is that you can't.

Even if you use the initializers' before and after properties to correctly specify the order in which they should be run, they are still asynchronous, and they don't wait for the previous initializer to have finished before starting their own work.

My advice is to have a single instance initializer and do something like the following:

export function initialize(application) {
  let store = application.__container__.lookup('service:store');
  let fSociety = application.__container__.lookup('service:service-FSociety');

  store.findAll('my-data').then(() => fSociety.start());
}

Upvotes: 1

Related Questions