如何在另一个服务中使用一个服务

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

本文关键字:服务 一个 另一个      更新时间:2023-09-26

我已经设置了两个服务,如下面的初始化器所示:

/* 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;

我可以从我的路由/控制器用户this.Sessionthis.Debug访问会话服务和调试会话。

我遇到的麻烦是从会话服务访问调试服务中的任何功能。

应用程序/服务/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;

应用程序/服务/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;

给出控制台错误的行是this.Debug.logSomething('Test');

错误为:Uncaught TypeError: Cannot read property 'logSomething' of undefined

为了从一个服务访问另一个服务中的函数,我需要做什么?

你只把这些对象注入到路由和控制器中。如果你想让它们可访问的话你需要互相注入

好的,所以我相信这是可能的。你只需要将Debug对象注入到会话1中。

你可以这样做:

首先注册你的工厂:

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

然后在会话中注入debug in:

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

或者你可以把debug注入到所有的服务中:

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