【问题标题】:ProvideIn - when should I use this new Angular 6 feature?ProvideIn - 我应该什么时候使用这个新的 Angular 6 功能?
【发布时间】:2018-11-19 13:51:02
【问题描述】:

在新版本 Angular 6 中添加了 ProvideIn。我想知道什么时候应该使用它。我应该只将它用于核心模块的服务吗?

当我尝试在我的 SomeCustomModule 中导入的服务中使用它时:

@Injectable({
  providedIn: SomeCustomModule,
})

我收到警告:WARNING in Circular dependency detected

【问题讨论】:

标签: angular angular6


【解决方案1】:
Using providedIn
Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn to root on the service's @Injectable() decorator. This tells Angular to provide the service in the application root.

src/app/user.service.ts
content_copy
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}
For more detailed information on services, see the Services chapter of the Tour of Heroes tutorial.

NgModule providers array
In apps built with Angular versions prior to 6.0, services are registered NgModule providers arrays as follows:


@NgModule({
  ...
  providers: [UserService],
  ...
})
If this NgModule were the root AppModule, the UserService would be a singleton and available throughout the app. Though you may see it coded this way, using the providedIn property of the @Injectable() decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable.

一般情况下,您只需要提供服务来提供服务,而使用 forRoot()/forChild() 来进行路由。但是,了解 forRoot() 如何确保服务是单例的将有助于您在更深层次上进行开发。

如果一个模块同时定义了提供者和声明(组件、指令、管道),那么在多个功能模块中加载该模块将重复服务的注册。这可能会导致多个服务实例,并且该服务将不再表现为单例。

There are multiple ways to prevent this:

Use the providedIn syntax instead of registering the service in the module.
Separate your services into their own module.
Define forRoot() and forChild() methods in the module.

【讨论】:

    猜你喜欢
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2012-09-22
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多