JonathanBristow
JonathanBristow

Reputation: 1065

Ember.js - How can I use a service in another service?

I have setup two services as shown in the below initializer:

/* Service Initaializers */
var Initaializer = {
    name: 'Services',
    initialize: function(Container, App) {
        /* Inject Session Service In To All Routes And Controllers */
        App.inject('route', 'Session', 'service:session');
        App.inject('controller', 'Session', 'service:session');
        /* Inject Debug Service In To All Routes And Controllers */
        App.inject('route', 'Debug', 'service:debug');
        App.inject('controller', 'Debug', 'service:debug');
    }
};

/* Export */
export default Initaializer;

I can access both the session service and debug session from my routes/controllers user this.Session and this.Debug.

What I am having trouble doing is accessing any of the functions in the Debug service from the session service.

app/services/debug.js

/* Debug Service */
var Service = Ember.Object.extend({
    /* Start Debug */
    init: function() {
        console.log('Debug Started!'); // This does appear in the console.  
    },  
    logSomething: function(i) {
        console.log(i);  // This does work from all routes/controllers. 
    }
});

/* Export */
export default Service;

app/services/sessions.js

/* Session Service */
var Service = Ember.Object.extend({
    /* Start Session */
    init: function() {  
        console.log('Session Started!'); // This does appear in the console.
        this.Debug.logSomething('Test'); // This gives an error.
    },
    sayHi: function() {
        console.log('Hello From The Session Service'); // I does work from all routes/controllers.
    }
});

/* Export */
export default Service;

The line that gives a console error is this.Debug.logSomething('Test');.

The error is: Uncaught TypeError: Cannot read property 'logSomething' of undefined

What do I need to do in order to access a function in another service FROM a service?

Upvotes: 2

Views: 2791

Answers (1)

abarax
abarax

Reputation: 6289

You have only injected these objects in to the route and controllers. You actually need to inject in to each other if you want them accessible

Ok, so I believe this is possible. You just need to inject your Debug object in to your session one.

You can do this like so:

First register your factories:

App.register('utils:debug', App.Debug);
App.register('service:session', App.Session);

And then inject the debug in to the session:

App.inject('service:session', 'debug', 'utils:debug');

Or you can inject debug in to all services:

App.inject('service', 'debug', 'utils:debug');

Upvotes: 3

Related Questions