1

We want to measure following Angular events and we know how to do this:

  • ngAfterViewInit of components and directives (through life cycle hooks)
  • routing navigations timings (through router events)
  • http calls through http client of common/http (through interceptor)

But we would like to log extra information:

  • the module class name and route component class name associated to a route
  • the module class name in which a given component is registered
  • the service or component who did the http call and associated module

How can we get this extra information?

stephan.peters
  • 963
  • 13
  • 35

1 Answers1

5

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.

Noémi Salaün
  • 4,866
  • 2
  • 33
  • 37