It’s a common mistake to confuse Dependency Injection (DI) and Dependency Inversion, in particular with Angular DI container. Only Dependency Inversion enables decoupling.
Following Uncle Bob’s Dependency Inversion Principle (DIP), we have to deal with abstractions. If dependencies are defined as concrete types, DI doesn’t perform dependency inversion.
DI with Angular + TypeScript can be confusing when dealing with classes:
@Injectable()
export class LoggerService {...}@Component(...)
export class AppComponent {
constructor(private logger: LoggerService) {...}
}
At first glance, it seems like AppComponent depends on the LoggerService class, a concrete implementation, breaking the DIP. But a TypeScript class can act as an interface:
class A {
constructor(public id: number) {}
}class B implements A {
id: number;
}const a: A = { id: 1 };
So, in the previous example, AppComponent depends only on the LoggerService class signature. LoggerService provider can return any object that follows its interface. DIP is in fact applied successfully.
