Injecting Service Providers in Angular 2.0 -


in angularjs 2.0 heroes tutorial explanation states if child component includes service in @component providers list, angular create separate instance of service specific child. don't understand if wanted use child component independently, , other times within parent component. seems severe restriction. i've playing angular 2.0, i've misunderstood something.

here's explanation angular.io site services section of heroes tutorial.

appendix: shadowing parent's service

we stated earlier if injected parent appcomponent heroservice herodetailcomponent, must not add providers array herodetailcomponent metadata.

why? because tells angular create new instance of heroservice @ herodetailcomponent level. herodetailcomponent doesn't want own service instance; wants parent's service instance. adding providers array creates new service instance shadows parent instance.

think , when register provider. understand scope of registration. careful not create new service instance @ wrong level.

here's link page came put in context.

if want component have own instance of service , @ same time have instance of parent's service have take @ @skipself()

consider following code

class service {     someprop = 'default value'; }  @component({   providers : [service] // child's instance }) class child {   constructor(     @skipself() parentsvc: service,      svc: service     ) {         console.log(psvc.someprop); // prints 'parents instance'         console.log(svc.someprop);  // prints 'default value'     } }  @component({   providers : [service] // parent's instance }) class parent {   constructor(svc: service) {     svc.someprop = 'parent instance';   } } 

with @skipself() telling component start dependency resolution parent injector (the name skipself says lot, guess).

you can read more visibility in host , visibility in angular 2's dependency injection @pascalprecht.

check plnkr working example.


Comments