在我的 angular2 应用程序中,我有几个模块,除了根模块之外的大部分都被延迟加载
Routes = [{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
...
{
path: 'item',
loadChildren: 'app/item/item.module#ItemModule'
}
在 ItemModule 中,我在“providers”下列出了一个 ItemSearchService
@NgModule({
imports: [
...
],
declarations: [
ItemDetailComponent,
ItemComponent,
ItemSearchComponent
],
exports: [
],
providers: [
ItemSearchService
]
})
因此,根据我对模块结构的理解,ItemDetailComponent 和 ItemSearchComponent 在构造函数中注入(inject)时应该获得相同的 ItemSearchService 实例。
export class ItemSearchComponent implements OnInit {
constructor(private http: Http, private itemSearch: ItemSearchService ... )
export class ItemDetailComponent implements OnInit{
constructor(private route: ActivatedRoute, private itemSearch: ItemSearchService ...)
然而,当我运行它时,只要我从 IteamSearchComponent 导航到 ItemDetailComponent,ItemDetailComponent 就会获得一个新的、单独的 ItemSearchService 实例,这当然不是预期的。
当我在根模块中提供 ItemSearchService 时一切正常,然后所有组件都获得相同的实例,但是当我将提供程序移至 ItemModule 时,似乎出了点问题。
这与 ItemModule 被延迟加载有什么关系吗?我在这里有点不知所措,现在这不是一个大问题,因为我可以在 AppModule 中将服务作为应用程序范围的单例提供,但我不想让我的所有服务都存在于根目录中从长远来看,我是不是错过了什么?
最佳答案
在 Angular 2 中有 Hierarchical Dependency Injection .
每个组件都有自己的注入(inject)器和充满父注入(inject)器的注入(inject)器树。您可以在提供的链接中阅读更多相关信息。
如果您对服务的构造函数进行调试,您会发现该构造函数被调用了两次。每个组件一次。
关于Angular2 服务 : Getting different instances in two components even though there's only one provider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020533/