Angular › Dependency Injection Providers & Injection Tokens

What is the difference between providing a service using useClass and useExisting?

Intermediate

Answer

useClass tells Angular to create a brand new instance of a different class when something asks for the original one, useful for swapping implementations, such as during testing. useExisting instead reuses an already existing instance of another service, making both names point to the exact same single instance rather than creating a separate one.
// useClass, creates a new, separate instance of a different class
providers: [{ provide: LoggerService, useClass: MockLoggerService }]

// useExisting, reuses the same existing instance under a different name
providers: [{ provide: OldLoggerService, useExisting: LoggerService }]
Real-world example A test suite replaces the real LoggerService with a MockLoggerService using useClass, letting tests verify logging behavior without actually writing anything to the real console output.

Common follow-ups: What would happen if useExisting were used instead of useClass in a testing scenario needing separate instances?;When is useExisting useful in real production code, not just testing?