作者:刺嫩芽豆豆 | 来源:互联网 | 2023-05-26 20:57
首先,我制作了一个没有Ember CLI的小型Ember应用程序.
我有这段代码.
window.MyApp = Ember.Application.create({
ready: function() {
this.register('session:current', MyApp.SessionController, { singleton: true });
this.inject('controller', 'session', 'session:current');
}
});
这很有效.
然后我决定用Ember CLI从头开始重写所有内容.
我编辑了文件app/app.js
并添加了ready
钩子,就像我以前的版本一样.
var App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver: Resolver,
ready: function() {
this.register('session:current', App.SessionController, { singleton: true });
this.inject('controller', 'session', 'session:current');
}
});
这不起作用.
会话控制器确实存在.那是文件的内容app/controllers/session.js
export default Ember.Controller.extend({
isLoggedIn: false,
});
我得到的错误信息是
TypeError: Attempting to register an unknown factory: `session:current`
它出现在浏览器中.
我用google搜索了这条消息,但我在Ember CLI中找不到依赖注入.
任何的想法?
1> Leeft..:
在ember-cli中,您可以使用ember generate service
和ember generate initializer
构建存根来实现这一目标,这远远好于摆弄app.js
.
你创建一个基本上像这样的服务:
// app/services/notifications.js
import Ember from 'ember';
export default Ember.Object.extend({
initNotifications: function() {
// setup comes here
}.on('init'),
// Implementation snipped, not relevant to the answer.
});
和初始化程序,它将服务注入到您需要它的应用程序的组件中:
// app/initializers/notifications-service.js
import Notifications from '../services/notifications';
export default {
name: 'notification-service',
after: 'auth-service',
initialize: function( container, app ) {
app.register( 'notifications:main', Notifications, { singleton: true } );
app.inject( 'component:system-notifications', 'notificationService', 'service:notifications' );
app.inject( 'service:auth', 'notificationService', 'service:notifications' );
}
};
这样,它就可以notificationService
在指定的组件上使用.
关于Ember依赖注入主题的文档可以在http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/找到.