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

查看:237
本文介绍了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 Service的新实例(从第一次调用它时清除数据).如何确保仅将Auth Service实例化一次,然后在不同组件之间访问该实例?

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?

推荐答案

这是将providerIn添加到服务级别的默认行为.根据 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中仅提供了under.请参考以下 answer .

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