Angular2 – Share data between components using services

You define it within your two components. So the service isn’t shared. You have one instance for the AppComponent component and another one for the Grid component.

@Component({
  selector: 'my-app',
  templateUrl: 'app/templates/app.html',
  directives: [Grid],
  providers: [ConfigService]
})
export class AppComponent {
  (...)
}

The quick solution is to remove the providers attribute to your Grid component… This way the service instance will be shared by the AppComponent and its children components.

The other solution is to register the corresponding provider within the bootstrap function. In this case, the instance will be shared by the whole application.

bootstrap(AppComponent, [ ConfigService ]);

To understand why you need to do that, you need to be aware of the “hierarchical injectors” feature of Angular2. Following links could be useful:

Leave a Comment