Can we inject an object or dependency through an Interface in Angular?
No, we cannot do dependency injection through Interface in Typescript Angular; it can be done in C# or Java. This is very important concept need to know for a single full stack developer as they are doing server side coding & JavaScript coding both. That is the reason interface use is generally avoided in front end or typescript framework, use classes instead for making it DI (Dependency Injection) capable.
0008-13- angular: Dependency Injection (DI) Token part 2 neatly explains
- Why Interface cannot be used as DI Token.
- It describes How Class can be used as a DI token and Interface cannot.
In angular, class name can be used as DI Token because it finally converts class name into function and function is uniquely defined that can be used to find out the dependency. But for Interface there is no existence at run time, once you compile your typescript into java script there is no existence of interface. That’s why we cannot use Interface as DI token in Typescript Angular. Snapshot of our video session below: