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

查看:32
本文介绍了如何在 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]);

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

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:

  • 您在引导应用程序时配置的根目录
  • 每个组件一个注入器.如果您在另一个组件中使用一个组件.组件注入器是父组件的一个子组件.应用程序组件(您在 boostrap 应用程序时指定的那个)将根注入器作为父注入器).

当 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天全站免登陆