[英]Where and how to specify initializer for an ember engine?
In my application, I have used initializers to inject services to routes, controllers and components. 在我的应用程序中,我已使用初始化程序将服务注入到路由,控制器和组件。 I am trying to use ember engine now. 我现在正在尝试使用余烬引擎。 I have shared my application services to my engine, but I need to inject the shared application services to the engine's routes, controllers and components using an initializer. 我已经向引擎共享了应用程序服务,但是我需要使用初始化程序将共享的应用程序服务注入引擎的路由,控制器和组件。
In my application, I can generate an initializer and inject the services. 在我的应用程序中,我可以生成一个初始化程序并注入服务。 How to do that in my engine? 如何在我的引擎中执行此操作?
This command should create the initializer in the proper folder under the in-repo-engine: 此命令应在in-repo-engine下的适当文件夹中创建初始化程序:
ember g initializer <init-name> -ir <engine-name>
Ideally, injecting a service into a controller/route/component is best done as stated in the other answer. 理想情况下,最好将服务注入到控制器/路由/组件中,如其他答案所述。
Refer: https://guides.emberjs.com/release/applications/dependency-injection/#toc_ad-hoc-injections 请参阅: https : //guides.emberjs.com/release/applications/dependency-injection/#toc_ad-hoc-injections
It may be substantially easier to require it where needed instead of injecting it everywhere. 在需要时而不是在各处注入它可能会更容易一些。
An example from the Ember Docs : Ember Docs中的示例:
import Component from '@ember/component';
import { inject as service } from '@ember/service';
export default Component.extend({
shoppingCart: service()
});
This would make the shopping cart service available here. 这将使购物车服务在此处可用。 You can do the same thing in routes and controllers and that service is a singleton so it will only be instantiated once and shares state between every location it is accessed. 您可以在路由和控制器中执行相同的操作,并且该服务是单例,因此它将仅被实例化一次,并且在每个访问位置之间共享状态。
This avoids needing to mess with creating an engine specific initializer entirely. 这避免了完全创建引擎特定的初始化程序的麻烦。
I actually found out that initializers for an engine can be configured similarly to the initializers for an application. 我实际上发现,引擎的初始化程序可以与应用程序的初始化程序类似地配置。 It can be specified in the lib/<engine>/addon/initializers
directory. 可以在lib/<engine>/addon/initializers
目录中指定它。
If you want to inject services to routes, components and controllers, you must first share the services from the app to the engine as explained in the engine docs . 如果要向路由,组件和控制器注入服务,则必须首先按照引擎文档中的说明将服务从应用程序共享到引擎 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.