Angular2 服务 : Getting different instances in two components even though there's only one provider

标签 angular typescript angular2-services

在我的 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/

相关文章:

Angular - 以构造函数以外的其他方式注入(inject)?

angular - 如何在 Angular Universal 中向 <body> 添加类?

angular - 如何让 Angular 使用我的 ssl 证书?

typescript - 从 VSCode 运行单独的 Mocha 测试

angular - 在组件或服务中使用 router.navigate 是最佳做法吗?

javascript - 如何在 angular2 服务调用期间进行过滤

node.js - 使用 angular4 将 hash-url 更改为 hash-bang url

javascript - 为每个 id 发出请求或按 ids 过滤请求

typescript - 没有第三方库的类型安全错误处理

javascript - 向多个父级发送事件以触发函数 Angular 5