typescript - Angular2 - Share data between components using services -
i have object want share between components angular2 app.
here source of first component:
/* app.component.ts */ // ...imports import {configservice} './config.service'; @component({ selector: 'my-app', templateurl: 'app/templates/app.html', directives: [grid], providers: [configservice] }) export class appcomponent { public size: number; public square: number; constructor(_configservice: configservice) { this.size = 16; this.square = math.sqrt(this.size); // here call service put data _configservice.setoption('size', this.size); _configservice.setoption('square', this.square); } }
and second component:
/* grid.component.ts */ // ...imports import {configservice} './config.service'; @component({ selector: 'grid', templateurl: 'app/templates/grid.html', providers: [configservice] }) export class grid { public config; public header = []; constructor(_configservice: configservice) { // issue here, _configservice.getconfig() empty object // had filled before this.config = _configservice.getconfig(); } }
and little service, configservice:
/* config.service.ts */ import {injectable} 'angular2/core'; @injectable() export class configservice { private config = {}; setoption(option, value) { this.config[option] = value; } getconfig() { return this.config; } }
my data not shared, in grid.component.ts, _configservice.getconfig()
line return empty object, filled before in app.component.ts.
i read docs , tutorials, nothing worked.
what missing ?
thanks
solved
my issue was injecting configservice twice. in bootstrap of application , in file i'm using it.
i removed providers
setting , worked !
you define within 2 components. service isn't shared. have 1 instance appcomponent
component , 1 grid
component.
@component({ selector: 'my-app', templateurl: 'app/templates/app.html', directives: [grid], providers: [configservice] }) export class appcomponent { (...) }
the quick solution remove providers
attribute grid component... way service instance shared appcomponent
, children components.
the other solution register corresponding provider within bootstrap
function. in case, instance shared whole application.
bootstrap(appcomponent, [ configservice ]);
to understand why need that, need aware of "hierarchical injectors" feature of angular2. following links useful:
Comments
Post a Comment