Search code examples
angularangular-services

Use a different service at module import


Here a simple implementation example of my issue:
https://stackblitz.com/edit/angular-gqy1lk

I've two pages that import test-generic module with a specific provided service (using ForChild) that inherit of TestGenericService service.

I use testMethod in each service to display in which page module, the component Generic was called.

As you can see in the stackblitz preview the "page1" link display Page2 instead of "Page1" string. And the page2 link display the correct string Page2.

It's seems that angular only take the last forChild call of TestGenericModule, in this case when Page2module is imported after Page1Module

What wrong with my usage of ForChild on providing Service?

Is is possible to import a module inside anothers modules, by provinding a specific service to inject, for the imported module scope only?

Thank you.


Solution

  • Ok I've found the solution :

    https://stackblitz.com/edit/angular-gqy1lk

    I just had to define which provider I want to use on the component level (providers) instead of the module level by using forChild.

    Now the Service Injection is correct from which component (Page1 or Page2) from where I've my TestGeneric component.