Expose logic in RouteReuseStrategy to some components (singleton)

Viewed 49

I have an Angular (v.12) application with a UI consisting of a fixed navigation bar and a dynamic frame where the different routes are loaded within a router-outlet.

I have also implemented my own RouteReuseStrategy so I can control when I want a "fresh" route or a stored snapshot.

All is working more or less as expected, but I see a clear optimization point that I would like to achieve.

I want to include some strongly related logic in my RouteReuseStrategy in addition of the standard methods (shouldReuseRoute, shouldDetach, store, etc.) that has to be accessible from some components.

Given that the RouteReuseStrategy class is indeed a service, my plan was to have an unique instance of this service shared by all these components (i.e. singleton service).

So, if I want to define this service as the routeReuseStrategy, in addition to being able to inject it in some components, I need to do this in my module definition:

...
providers:    [MyRouteReuseStrategy, {provide: RouteReuseStrategy, useClass: MyRouteReuseStrategy}]
...

The problem is that this way Angular generates two instances of the service. One internal for the RouteReuseStrategy and the other one for the injected service. This is causing me some issues.

Do you know any alternative to expose some of the logic in MyRouteReuseStrategy keeping it a singleton service?

I have also tried to define the service as root-provided with the same result (two instances).

I can obviously separate the logic into a different service, but for me it makes totally sense to encapsulate all the logic in a unique service extending the RouteReuseStrategy.

I have been stuck with this issue for a long time, so any answer will be of great help.

0 Answers
Related