Angular 6创建单例服务

编程入门 行业动态 更新时间:2024-10-27 18:28:11
本文介绍了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创建单例服务

本文发布于:2023-11-15 11:20:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!