【问题标题】:Angular2 service: Getting different instances in two components even though there's only one providerAngular2 服务:即使只有一个提供者,也可以在两个组件中获取不同的实例
【发布时间】: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


    【解决方案1】:

    在 Angular 2 中有 Hierarchical Dependency Injection。

    每个组件都有自己的注入器和填充了父注入器的注入器树。您可以在提供的链接中了解更多信息。

    如果您在服务的 ctor 上进行调试,您会发现该 ctor 被调用了两次。每个组件一次。

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 2019-08-06
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多