I'm currently working on a project using Angular (6.0.7
) and I am in the process of creating a service using the new:
@Injectable({
providedIn: 'root'
})
My question is, how can I specify an interface for dependency injection?
The issue at hand
In my project, I have two services - Authentication.service and SessionStorage.service. I want to inject the session storage service into the authentication service. This can be achieved like this:
constructor(private sessionStorage: SessionStorage) {
}
However, I want to define an interface
above these services (to allow for implementing both local storage service and session storage service). Therefore, it makes sense to type the injected class with the interface. Unfortunately, Angular 6 does not support this feature in the same way as Angular 5 and earlier versions.
So, how can I assign a type to the injected class in this global service using my interface?
What I've attempted so far
The typings for Angular services include an InjectableProvider
, but it doesn't align with any parameters of the siblings of InjectableProvider
, leading to compiler and tslint errors.
@Injectable({
providedIn: 'root'
}, {provide: IStorageService, useClass: SessionStorage})