在VS forRoot中提供了Angular服务 [英] Angular service providedIn VS forRoot
问题描述
我想知道这两个代码块是否相等.
I'd like to know if these two blocks of code are equivalent or not.
我可以使用 providedIn
和 forRoot
相同的结果吗?
Can I use providedIn
with the same result of forRoot
?
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
}
vs
@Injectable()
export class MyService {
constructor() { }
}
@NgModule({
imports: []
})
export class MyModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
MyService
]
};
}
}
@NgModule({
imports: [
MyModule.forRoot()
],
bootstrap: [AppComponent]
})
export class AppModule { }
[我仍将我的 MyModule
与 providedId
单例服务一起使用一次
[I would still keep my MyModule
for single use with the providedId
singleton services]
推荐答案
providedIn
将基于该值直接注入 service
-如果它是'root',它将直接注入根 module
-这将帮助您停止在模块 [providers]
providedIn
will directly injects the service
based on the value - if its 'root' it will directly inject in root module
- this will help you to stop adding your service
in module [providers]
Angular将在 module
中注入服务-如果您使用的是惰性加载模块-Angular将在每次加载其他模块时创建新的注入器
Angular will inject the service in the module
- If in case you are using Lazy loading modules - angular will create new injectors whenever you load other modules
如果您使用延迟加载,最好在模块上进行 forRoot()
注入,并确保您的 service
不创建多个注入器
If you use Lazy loading is better to go with forRoot()
injection on the modules and make sure your service
doesn't create multiple injectors
希望这对您有帮助-编码愉快!!
Hope this helps you - Happy coding !!
选中此链接以获取更多信息
这篇关于在VS forRoot中提供了Angular服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!