An elegant alternative to switch\case using Angular’s dependency injection.

Switch statements tend to grow and become ugly and nasty beasts, no matter how well you take care of them.

For example, imagine you have this piece of code in your Angular service:

We can leverage Angular’s dependency injection to help us clean up the switch statement.

The solution is built by working with an interface and InjectionToken. Each class that implements the interface will hold the logic found under a single case block. Each class will be registered to Angular’s DI under our InjectionToken using the multi-option.

Let's start with defining the interface that will later be used as the type that will be injected into the service:

Next, we need to create an InjectionToken based on the above interface:

Now, for every case block, we will create a class that will implement our interface:

We can then register the classes to Angular’s DI using the InjectionToekn:

When multi is set to true it means that our InjectionToken can be registered multiple times as provide and when injecting the token we get back all classes\values under that token:

Now we can get rid of the switch statement completely and look for the CaseLogicHandler we need and then invoke the logic:

That’s it.

The solution is more verbose than the switch statement but provides a much cleaner and elegant code.

--

--