Angular: How to get component dependency on console?

I focus on component component in dev tools and can do the following:

ng.probe($0) 

to get a special DebugElement object. Now we can get its injector:

  ng.probe($0).injector 

Now I would like to get the dependency defined on this component. A dependency is defined as a class, so I should do something like this:

 ng.probe($0).injector.get(MyService) 

BUT! The service is not defined in the console area. If I make it a line:

  ng.probe($0).injector.get('MyService') 

obviously it also does not work.

I am trying to reverse engineer ReflectiveInjector.get , but so far no luck. Any ideas?

+5
source share
1 answer

We must pass the token to the injector.get method, as announced. We cannot use the string if the class is declared as a token.

Angular stores providers declared inside a 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 he uses elementInjector to get the dependency.

enter image description here

DebugElement retrieves information about tokens provided by the 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 have declared the provider in the providers array of component metadata, the token becomes available in the providerTokens array.

So we can get addicted by writing

 ng.probe($0).injector.get(ng.probe($0).providerTokens .find(x => x.name === 'MyService')) 

see also

+3
source

Source: https://habr.com/ru/post/1269876/


All Articles