We know that placing @Injectable({ providedIn: 'root' }) on a service makes it globally available.
However, Angular's Dependency Injection (DI) system is incredibly powerful and customizable.
You can control exactly how and what gets injected by configuring "Providers" manually.
When you inject a service, Angular looks for a "provider" that knows how to create it.
You can manually configure providers at the component level using the providers array.
This creates a brand new, isolated instance of the service strictly for that component!
@Component({
selector: 'app-isolated',
template: '<p>Isolated instance!</p>',
// Overrides the global service with a fresh instance
providers: [LoggerService]
})
export class IsolatedComponent { }
You don't always have to inject exactly what was requested.
Using useClass, you can trick a component into using a completely different service (like an ApiMockService for testing).
Using useValue, you can inject plain values (like strings or configuration objects) instead of an entire class.
providers: [
// When a component asks for ApiService, give them ApiMockService instead!
{ provide: ApiService, useClass: ApiMockService },
// Injecting a simple configuration object
{ provide: 'API_URL', useValue: 'https://test-api.example.com' }
]
In the example above, using a string 'API_URL' as a provider token is dangerous because strings can clash.
To inject simple values securely, Angular provides InjectionToken.
This creates a guaranteed unique token that you can use to inject configuration data anywhere.
import { InjectionToken, Inject } from '@angular/core';
// 1. Create the unique token
export const API_URL = new InjectionToken<string>('API_URL');
// 2. In a component, inject it using the @Inject decorator
constructor(@Inject(API_URL) public apiUrl: string) {
console.log('Connecting to:', apiUrl);
}
If you add a service to the 'providers' array inside a specific @Component decorator, what happens?
Which property is used in the providers configuration to swap out a requested service with a Mock service for testing?