在Angular2中启动时实例化服务 [英] Instantiate service on startup in Angular2

查看:157
本文介绍了在Angular2中启动时实例化服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(单例)服务,该服务在构造函数中包含一些代码,应在启动后直接运行.加载应用程序后,必须立即创建该实例.

I hava a (singleton) service that contains some code in the constructor which should be run directly after startup. That menas an instance has to be created immidiately when the app is loaded.

实例化服务的一种可能性是将其放在应用程序组件的构造函数中:

One possibility to instanciate the service is to put it in the constructor of the app component:

export class AppComponent {

  constructor(private mySercive: MyService
...

,但是由于我从未在此组件中使用myService,因此会收到类似mySerive is not used的警告,并且我团队中的其他人可能会删除该服务.有没有办法实例化应用程序模块内部的服务?

but since I never use myService in this component I will get a warning like mySerive is not used and someone else in my team might delete the service. Is there a way to instanciate the serivce inside the app module?

推荐答案

您可以提供一个虚拟APP_INITIALIZER并将其像一样传递

You can provide a dummy APP_INITIALIZER and pass it as dependency like

@NgModule({
  providers: [{provide: APP_INITIALIZER, useMulti: true, deps: [MyService], useFactory: (myService) => null}]

这篇关于在Angular2中启动时实例化服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆