I put focus on component element in dev tools and can do following:
ng.probe($0)
to get the special object "DebugElement". Now we can get its injector:
ng.probe($0).injector
now I would like to get a dependancy that is defined on this component. Dependancy is defined like a class, so I should do something like so:
ng.probe($0).injector.get(MyService)
BUT! Service is not defined in console scope. If I make it a string:
ng.probe($0).injector.get('MyService')
obviously it also does not work.
I'm trying to do reverse engineering on ReflectiveInjector.get, but no luck for now. Any ideas?
We have to pass token to injector.get
method as it was declared. We can't use string if we declared class as token.
Angular keeps providers declared within component in ngfactory Plunker
function View_App_Host_0(_l) {
return jit_viewDef0(0,[(_l()(),jit_elementDef1(0,null,null,2,'my-app',[],null,null,
null,jit_View_App_02,jit__object_Object_3)),jit_providerDef4(4608,null,jit_MyService5,
jit_MyService5,[]),jit_directiveDef6(49152,null,0,jit_App7,[],null,null)],null,
null);
}
And it uses elementInjector to get dependency.
DebugElement
gets information about tokens provided to current node
get providerTokens(): any[] {
const tokens: any[] = [];
if (this.elDef) {
for (let i = this.elDef.index + 1; i <= this.elDef.index + this.elDef.childCount; i++) {
const childDef = this.elView.def.nodes[i];
if (childDef.flags & NodeFlags.CatProvider) {
tokens.push(childDef.provider !.token);
}
i += childDef.childCount;
}
}
return tokens;
}
After we declared provider within providers
array of component metadata the token becomes available in providerTokens
array.
So we can get dependency by writing
ng.probe($0).injector.get(ng.probe($0).providerTokens
.find(x => x.name === 'MyService'))
See also