[英]Ember.js - How can I use a service in another service?
我已经设置了两个服务,如下面的初始化程序所示:
/* 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.Session
和this.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);
然后将调试插入到会话中:
App.inject('service:session', 'debug', 'utils:debug');
或者,您可以将调试插入到所有服务中:
App.inject('service', 'debug', 'utils:debug');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.