Angular 6 创建单例服务 [英] Angular 6 Creating Singleton Service

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

问题描述

我知道 Angular 6 中必须创建单例服务的方式发生了一些变化.我有一个身份验证服务,需要为访问它的每个组件构造一次.我将提供者设置为服务的根:

I understand there have been some changes in Angular 6 with the way singleton services have to be created. I have an Auth Service that needs to be constructed once for each component that accesses it. I set the provider to root for the service:

@Injectable({
  providedIn: 'root'
})

在我的 app.module.ts 文件中,我将 AuthService 设置为我在 NgModule 中的提供者之一.但是,每当我在使用 Auth 服务的不同组件之间进行路由时,它都会创建一个新的 Auth 服务实例(从第一次调用时清除数据).如何确保身份验证服务仅实例化一次,然后在不同组件之间访问该实例?

And in my app.module.ts file, I set AuthService as one of my providers in NgModule. However, whenever I route between different components that use the Auth service, it creates a new instance of the Auth Service (clearing data from the first time it was called). How do I ensure that the Auth Service is only instantiated once, and then access that instance among different components?

推荐答案

这是将 providedIn 添加到服务级别的默认行为.根据 Docs

That's the default behaviour of adding providedIn to the service level. As per Docs

providedIn 这里告诉 Angular 根注入器负责用于创建 HeroService 的实例.服务是只要这种方式自动提供给整个应用程序,不需要在任何模块中列出.

providedIn here tells Angular that the root injector is responsible for creating an instance of the HeroService. Services that are provided this way are automatically made available to the entire application and don't need to be listed in any module.

在您的情况下,只需删除 providedIn: 'root' 并且仅在 module.ts 下提供.请参阅以下答案.

in your case just remove the providedIn: 'root' and have only under provides in the module.ts. Refer the following answer.

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

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