【发布时间】:2016-12-07 14:51:03
【问题描述】:
在我的 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 在构造函数中注入时应该得到相同的 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 ...)
然而,当我运行它时,一旦我从 ItamSearchComponent 导航到 ItemDetailComponent,ItemDetailComponent 就会获得一个新的、单独的 ItemSearchService 实例,这当然不是有意的。
当我在根模块中提供 ItemSearchService 时一切正常,然后所有组件都获得相同的实例,但是当我将提供程序移动到 ItemModule 时,似乎出了点问题。
这可能与 ItemModule 被延迟加载有关吗?我在这里有点茫然,现在这不是一个大问题,因为我可以在 AppModule 中将服务作为应用程序范围的单例提供,但我不想让我的所有服务都存在于根目录中从长远来看是模块,所以我在这里遗漏了什么吗?
【问题讨论】:
标签: angular typescript angular2-services