Search code examples
angularangular-routing

Switching between services after route change


My app has a lot of components that are almost the same. Every component contains chart with similar options and different data series. All data fetching and manipulation takes place in service.

I've came up with idea that I don't need so many almost the same components and I'll just pass options and series through service. That will reduce a lot of boilerplate. But is this a good practice? Is it better to have 10 services and 10 components or 10 services and 1 component that will change service when the route will change?

Also that is just theory. I've tried to do this but I'm stuck on how to provide another service after route change and then re-init the component. Couldn't find any informations about that, so any advice would be very helpful.

I've recreated this problem on StackBlitz.


Solution

  • You can leverage abstract classes, dependency injection and factories, let me explain: first of all you can create a Service abstract class which will be the model for your concrete services and the injected token in your component, then use a serviceFactory to inject the concrete service class in the component depending on runtime parameters (such as route path for example)

    I did that in this stackblitz

    You'll see that by navigating to /template the service1 is used and the number 1 is shown.
    And by navigating to /template2 the service2 is used and the number 2 is shown

    Let me know if you have questions.