Angular 6创建单例服务

Dan*_*Dan 7 authentication angularfire2 angular angular6

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

@Injectable({
  providedIn: 'root'
})
Run Code Online (Sandbox Code Playgroud)

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

Saj*_*ran 6

这是将providerIn添加到服务级别的默认行为。按照Docs

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

在您的情况下,只需删除providedIn: 'root'module.ts 中的且仅包含under即可。请参考以下答案