What does the useExisting key do?
The useExisting key tells Angular:
"Do not create a new service, use the existing instance of another one."
Example:
ts
providers: [
{ provide: AuthService, useClass: AuthService },
{ provide: LoginService, useExisting: AuthService }
]Now, if something requests LoginService, Angular returns the same object as AuthService.
When this is needed:
- when two different tokens must point to the same service;
- to avoid duplicating instances or causing conflicts;
- to share the same state under different names.
Summary:
useExisting is a way to tell Angular: "use the dependency that already exists instead of creating a new one."
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.