[英]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.