I am developing an application using angular2. I have a scenario where I need to pass complex data (array of objects) from one component to another component(they are not pa
camaron is right. Your mistake is that you declare UtilityService
twice:
SearchComponent
.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:
@NgModule
which has both SearchComponent
and TransferComponent
in its declarations. 9 times out of 10 this is the right solution!@Component
which is a parent of both SearchComponent
and TransferComponent
. 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) { }
}