Search code examples
angulartypescriptdebuggingprofilerinstances

How to count the number of instances for a given class in an Angular app?


Following up reading the links below about impure and pure pipes in Angular applications:

I wanted to see by myself the instances created by an Angular application, but I am not even sure this is actually possible. Not necessarily for the pipes but for anything. Say for the components and others.

For example this would could help me to understand I would like to have a better understanding of when the instances are created in regard to the digest cycle.

Any debugging solution / profiler for that purpose?


Solution

  • I am not sure about the debugging/profiler that tool because I've never needed it for this reason, but this might help you understand the instancing.

    Components, Pipes, and Directives are instanced for each use. That means they are fully constructed each with the separate life cycle.

    Services are the ones which can be singletons or instanced for each use. A lot of the services you write in-app are singletons. If you think about singletons you can imagine the service that gets data from a server, state management service (store), service that displays some info to a user on demand (toastr), language service (init translations and switching language), ...

    There is a lot to cover on the topic of Singleton services so I recommend reading https://angular.io/guide/singleton-services .

    If you want to visualize the instances that are being made, it can easily be done by writing some simple logs in the constructor (constructor is being when a new instance of a class is being created).

    To log a name of the class every time it is constructed add console.log(this.constructor.name) to your constructor of class you want to log.