I am just curious about differences, and the different use cases, between InjectionToken and Injectable. I have a service similar to below:
// Service defintion:
export const MY_SERVICE_TOKEN = new InjectionToken<IMyService>('My Service', {
factory: () => new MyService(),
providedIn: 'root'
});
export interface IMyService {
readonly subject: BehaviorSubject<string>;
}
export MyService implements IMyService {
constructor() {}
subject: BehaviorSubject<string> = new BehaviorSubject<string>('initial value')
}
// Usage case:
@Component(/* Removed for Brevity */)
export class MyComponent {
constructor(@Inject(MY_SERVICE_TOKEN) private myService: IMyService) {
}
}
Initially my service class had the @Injectable directive on it with the providedIn: 'root' property set. But I ended up removing it for curiosities sake and the DI still worked fine. Logically it make sense as I am not injecting the class but the interface via a Token. So my question is, should I still be adding the Injectable directive to the class? Or if by doing so would it register two services? One for the class decorated with the Injectable and one for the interface registered via the Token?
In what scenario would I use Injectable over an InjectionToken?
And a bonus question if the Injectable as a useClass property by I cannot define it on a interface? Why would you decorate a service as Injectable to only return a different type via useClass? Is it to do with abstract classes?
Just for the sake of giving this post an answer:
When you provideIn: root you are providing this resource in the whole applicaction.
When you use @Inject in a component or module this resource only will only live at those levels of the application.
On this official documentation you can find very useful information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With