Find the caller of a function
You can take advantage of the call stack to find the service or component that make the call. See this question
How do you find out the caller function in JavaScript?
Find the module of a component
To get the declaring module of a given component, you can use the ComponentFactoryResolver
.
When resolving a component, it returns a ComponentFactory
. But when looking at the source code, we can see that ComponentFactory
is an abstract class. In fact, the real class is ComponentFactoryBoundToModule
which is aware of its module.
It is aware, but it is private. If it is just for debuging or logging, I think you can ignore TypeScript and go get this private property. In runtime, the privacy is lost, so you can do something like
constructor(private resolver: ComponentFactoryResolver) {
const factory = resolver.resolveComponentFactory(HelloComponent);
console.log('the factory:', factory);
// Access the private ngModule property.
const ngModuleRef: NgModuleRef<any> = (factory as any).ngModule;
console.log('the module name:', ngModuleRef.instance.constructor.name)
}
See this StackBlitz for working example
Find the component of a route
I don't have the time to search deeply on this subject, I'll try it tomorrow if I find the time
I think you can get all the information you need with the router events. They give access to the resolved route, which contains all the configuration, including the component that should be inserted in the router outlet.