如何在Angular 2中创建单例服务? [英] How do I create a singleton service in Angular 2?

查看:88
本文介绍了如何在Angular 2中创建单例服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到,引导时的注入应该让所有子进程共享相同的实例,但是我的主要和标头组件(主要应用程序包括标头组件和路由器出口)都分别获得了我的服务的单独实例.

I've read that injecting when bootstrapping should have all children share the same instance, but my main and header components (main app includes header component and router-outlet) are each getting a separate instance of my services.

我有一个FacebookService(用于调用Facebook javascript api)和一个使用FacebookService的UserService.这是我的引导程序:

I have a FacebookService which I use to make calls to the facebook javascript api and a UserService that uses the FacebookService. Here's my bootstrap:

bootstrap(MainAppComponent, [ROUTER_PROVIDERS, UserService, FacebookService]);

从我的记录看来,引导调用完成了,然后我看到在运行每个构造函数,MainAppComponent,HeaderComponent和DefaultComponent中的代码之前先创建了FacebookService,然后创建了UserService:

From my logging it looks like the bootstrap call finishes, then I see the FacebookService then UserService being created before the code in each of the constructors runs, the MainAppComponent, the HeaderComponent and the DefaultComponent:

推荐答案

Jason完全正确!这是由依赖项注入的工作方式引起的.它基于分层注入器.

Jason is completely right! It's caused by the way dependency injection works. It's based on hierarchical injectors.

Angular2应用程序中有几个注入器:

There are several injectors within an Angular2 application:

  • 引导应用程序时配置的根目录
  • 每个组件的注射器.如果在另一个组件内部使用组件.组件注入器是父组件之一的子代.应用程序组件(在增强应用程序时指定的组件)将根注入器作为父组件.

当Angular2尝试在组件构造函数中注入某些东西时:

When Angular2 tries to inject something in the component constructor:

  • 它查看与组件关联的注射器.如果有匹配的实例,它将使用它来获取相应的实例.这个实例是延迟创建的,并且是该注入器的单例.
  • 如果此级别上没有提供者,它将查看父注入器(依此类推).

因此,如果要为整个应用程序设置一个单例,则需要在根注入器或应用程序组件注入器的级别定义提供程序.

So if you want to have a singleton for the whole application, you need to have the provider defined either at the level of the root injector or the application component injector.

但是Angular2将从底部看进样器树.这意味着将使用最低级别的提供程序,并且关联实例的范围将为该级别.

But Angular2 will look at the injector tree from the bottom. This means that the provider at the lowest level will be used and the scope of the associated instance will be this level.

有关更多详细信息,请参见此问题:

See this question for more details:

这篇关于如何在Angular 2中创建单例服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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