ember-cli-clock icon indicating copy to clipboard operation
ember-cli-clock copied to clipboard

Service wont start unless I console log clock

Open jrock2004 opened this issue 8 years ago • 4 comments

So I am trying to inject the clock service in my model. But it will not start unless I interact with the clock service.

clock: Ember.inject.service('booking-counter'),
  isAvailable: Ember.computed('deadline', 'isbookable', 'clock.time', 'clock', function() {
    console.log(this.get('clock'));

    if(!this.get('isbookable')) {
      return false;
    }


    return moment(this.get('deadline')) > moment();
  })

If I take out the console log the service will not start. Any ideas on what I am doing wrong?

jrock2004 avatar May 20 '16 17:05 jrock2004

Interesting. Does adding clock (instead of clock.time) to Ember.computed have any effect?

jerel avatar May 23 '16 21:05 jerel

I have the same problem, adding a binding to clock does not work. The init method on the service is not invoked, so it is not started.

willemdewit avatar Nov 09 '16 15:11 willemdewit

manually calling start in the init handler of my own controllers/components worked as well

SirZach avatar Dec 05 '16 05:12 SirZach

I just ran into this and learned a bit about how service injection works. Hopefully this helps anyone else running into this issue...

Services are lazily injected into Ember objects, so clock will be null until something tries to access/get it.

One way to make sure your clock service gets injected is to make your computed property accesses it.

So, instead of writing...

isAvailable: computed('availableDate', 'clock.date', function() {
  return moment(this.availableDate).isAfter(new Date());
})

you should write something the accesses the clock, forcing injection to take place. For example:

isAvailable: computed('availableDate', 'clock.date', function() {
-  return moment(this.availableDate).isAfter(new Date());
+  return moment(this.availableDate).isAfter(this.clock.date);
})

ryanto avatar May 22 '19 05:05 ryanto