Ginty
Ginty

Reputation: 3501

How to inject a service into every component in Ember JS

I have a session service that I want to inject into every component, according to the docs, this should work:

app.register('service:session', Session, { singleton: true });
app.inject('controller', 'session', 'service:session');
app.inject('route', 'session', 'service:session');
app.inject('component', 'session', 'service:session');

It works for controllers and routes, but generated components do not pick up the service.

How can I make this work?

I know that some are going to say that giving a component access to a service is bad form, but then again, the Ember core team are advising that controllers are going to be replaced by route-able components and in which case it seems perfectly reasonable.

I am following this technique to shim route-able components in the meantime: http://emberigniter.com/should-we-use-controllers-ember-2.0/

Thanks!

Upvotes: 1

Views: 3470

Answers (2)

ykaragol
ykaragol

Reputation: 6221

Try to use "reopen" Ember.Component. You can look to guide for reopen and reopenclass

Example:

Ember.Component.reopen({
    service: Ember.inject.service()
});

Upvotes: 2

Manu Benjamin
Manu Benjamin

Reputation: 997

we can inject services to component. Did you try with the following?

service : Ember.inject.service('service')

component.js

export default Ember.Component.extend({

    service : Ember.inject.service('service'),

    actions : {

    }
});

Upvotes: 0

Related Questions