Dynamically Injecting Service - angular Dependency Injection Project coding

1 minute read

In our eighth angular coding session Angular Coding Session Learn Dependency Injection | Practical | 8/8, we will see how to dynamically inject the console or http logger based on the configuration settings in our project. Here we will see why http logger constructor will not be called even though we have provided it in the Http logger.

We coded our project to provide it in the root and it doesn’t mean it will create an instance; it’s just that it is available there. Whenever somebody will ask, it will go to Injector; it will check if it has value or not, if not then it will go to the provider of that node. If it is module then it will ask module’s provider. It will ask module provider, you have it or not and if not how to create it. Node or module’s provider will create it and provide it to you and then Injector will use it.

But in our demo session if anybody needs logger, it will just ask Logger as base class. In this way we made service to be initialized whenever it is asked. If we go to the line item component, we will see there it is injected as Logger. So unless we will ask http logger or console logger explicitly, we will not get the instance.

This is what we should have in our Architecture to make our code robust and flexible. Snapshot from our demo coding session below: