Dependency injection creates new instance each time if used in router submodule
See original GitHub issueI’m submitting a … (check one with “x”)
[X] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
Current behavior My application is divided into modules. Router navigates between modules, each child modules has some providers and some components. I expect application to reuse services injected to components within one module. However, when I navigate, service constructor is called each time component is loaded.
RootModule:
RouterModule.forRoot([
{ path: '', component: EmptyComponent },
{ path: 'module', loadChildren: () => SubModule },
])
SubModule:
RouterModule.forChild([
{ path: 'test1', component: TestComponent1 },
{ path: 'test2', component: TestComponent2 },
])
...
providers:
[
TestService
],
Each time I navigate between /module/test1 and /module/test2 - TestService constructor is called
Expected behavior If test1 and test2 are defined as routes in RootModule, only one instance of TestService is created. I expect SubModule to inject the same instance of TestService if I navigate between its components.
If I move TestService provider to RootModule - works as expected
Minimal reproduction of the problem with instructions https://github.com/peku33/angular2-dependency-injection-failure
What is the motivation / use case for changing the behavior? Most of components of one of modules uses a service that opens and maintains WebSocket connection. Each time a service is spawned, new connection is opened. I definitely want to reuse the component and keep single connection open than close and reopen it every time user navigates between pages.
Please tell us about your environment: Everything is up to date, browser - Chrome
-
Angular version: 2.0.X Have ‘latest’ for almost everything in package.json @angular/core@2.2.0
-
Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
-
Language: [all | TypeScript X.X | ES6/7 | ES5]
-
Node (for AoT issues):
node --version=
Issue Analytics
- State:
- Created 7 years ago
- Reactions:15
- Comments:29 (4 by maintainers)

Top Related StackOverflow Question
I’m experiencing this issue as well. Is it still a present bug or is the problem on my end?
Angular 5.1.3
@guojenman I know. But the problem is, that DI creates multiple objects for components inside THE SAME module