Use an Abstract Class as DI Token for your Services in Angular

Share this video with your friends

Send Tweet

As your application grows, you may have different kind of implementations of the same service structure. Take for instance a logging service with different concrete implementation flavors. Something that might immediately jump into your mind is to use an interface to abstract the concrete implementation of these specific service instances and use the interface for fetching the instance in your components. Unfortunately, TypeScript interfaces won’t work with Angular’s dependency injector.

In this lesson we will learn why and how we can circumvent TypeScript interfaces.

Enoh Barbu
Enoh Barbu
~ 7 years ago

I did not get your point with this. You should post concrete examples

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

The point here is about using a generic base type and specify concrete instances for it via the DI mechanism. This is a typical scenario when you deal with dependency injection. What I'm showing in this lesson is how you can achieve that, and especially that it's not possible to use interfaces, as many people wrongly assume. The reason is that TypeScript interfaces - as you might know - only exist at compile time and thus Angular cannot use them at runtime to determine the concrete instance of a class to inject. Thus, in this example I'm using an abstract class for this :)

Enoh Barbu
Enoh Barbu
~ 7 years ago

So it seems that this is a problem related to the ecosystem TS/ES compiling. It doesn't have anything to do with Angular...

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

Exactly 🙂