angular - Component dependencies & Using life cycle hooks as logic -
the problem :
<div class="appcontainer"> <my-cube-container></my-cube-container> <my-toolbox></my-toolbox> </div>
my-toolbox
calls service inside constructor. service a
calls service b
, set values service. my-cube-container
calls service b
in constructor. when my-cube-container
calls service b
values aren't initialized.
possible resolution ?:
- using life cycle hooks: if 1 service called in onnginit() called after other service used in component constructor. feels bit wrong , not explicit.
- tell angular component dependent of one. think more explicit, , that.
you have several options, keep things way are, move calls services nginit()
logic should inside method , not on constructor. make life harder when comes testing. after create observable values on service b
, make <my-cube-container></my-cube-container>
subscribe observable, gets notified when values available.
another option creating new component wrap 2 components. component responsible feed data <my-cube-container>
, <my-toolbox>
, this:
<my-wrapper> <my-cube-container [values]="servicebvalues"></my-cube-container> <my-toolbox (setvalues)="setvalues($event)"></my-toolbox> </my-wrapper>
and ts
code this:
import {component} 'angular2/core'; @component({ selector: 'my-wrapper', template: ` <my-wrapper> <my-cube-container [values]="servicebvalues"></my-cube-container> <my-toolbox (setvalues)="setvalues($event)"></my-toolbox> </my-wrapper> ` }) export class mywrappercomponent { public servicebvalues; constructor(private servicea: serviceb, private serviceb: serviceb) setvalues(event) { console.log(event); this.servicea(event); this.servicebvalues = this.serviceb.getvalues(); // guess available now, if not use promises or observables } }
so <my-wrapper>
responsible logic , actual components more dummy components show data.
Comments
Post a Comment