camaron is right. Your mistake is that you declare UtilityService
twice:
- Once in the providers of
SearchComponent
. - Once in the providers of
TransferComponent
.
You should declare the service ONLY ONCE to make sure both components get the same instance. For this you can choose between either of these options:
- Declare the service in the providers of a
@NgModule
which has bothSearchComponent
andTransferComponent
in its declarations. 9 times out of 10 this is the right solution! - Declare the service in the providers of a
@Component
which is a parent of bothSearchComponent
andTransferComponent
. This might not be feasible depending how your component tree looks.
Following option #1, you end up with:
@NgModule({
imports: [CommonModule, ...],
// Look, the components injecting the service are here:
declarations: [SearchComponent, TransferComponent, ...],
// Look, the service is declared here ONLY ONCE:
providers: [UtilityService, ...]
})
export class SomeModule { }
Then inject UtilityService
in your components’ constructors WITHOUT REDECLARING IT in the components’s providers:
@Component({
selector: 'foo',
template: '...',
providers: [] // DO NOT REDECLARE the service here
})
export class SearchComponent {
constructor(private utilityService: UtilityService) { }
}
@Component({
selector: 'bar',
template: '...',
providers: [] // DO NOT REDECLARE the service here
})
export class TransferComponent {
constructor(private utilityService: UtilityService) { }
}