在新版本Angular 6中添加了ProvideIn。我想知道我什么时候应该使用它。我应该只使用Core Module提供的服务吗?
当我尝试在我的SomeCustomModule中导入的服务中使用它时:
@Injectable({
providedIn: SomeCustomModule,
})
我发出警告:WARNING in Circular dependency detected
答案 0 :(得分:0)
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.
通常,您只需要ProvideIn提供服务,而只需要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.