Search code examples
angulardependency-injectionlazy-loading

How to provide alternative class to Lazy Module


I have a simple app with a lazy-loaded featureModule. The main page has a button for incrementing a global counter by 1, and a button in the featureModule increments the same counter by 10.

I want to use a singleton service for managing the count, and I want this service to be extended and have its increment() method overridden (to increment by 10) when it is provided to the feature module.

It seems that the way to go is to use a provider with "useExisting", but I still end up with 2 instances.

Here's the stackblitz link: https://stackblitz.com/edit/angular-fuk9yc-hysfrw

Can someone solve this mystery for me?


Solution

  • A couple of comments regarding your solution.

    1. The useExisting it's used when you have too many methods in your serivce and you just want to use some of them, it's like an alias for your SharedService
    2. Your shared service is provided in root so will be accesible from the whole solution, when you provide it in your lazyModule you are generating other instance that will exist in the scope of your new module.

    Regarding a solution, you can have your CustomerService that increment by 10, and update the count in the SharedService, you can provide it since is scoped in root.

    You will have to remove the useExisting of course.