I am building an application with Angular (6.0.7) and I am trying to create a service with the new:
@Injectable({
providedIn: 'root'
})
But how can I type an injection with an Interface?
The problem
I have 2 services, Authentication.service and SessionStorage.service. I want to inject the sessionstorage into the authentication service. That can be done via:
constructor(private sessionStorage: SessionStorage) {
}
No problem there. But for Object Orientated purposes I want to have an interface above this service (so that I can implement both localstorage service as sessionstorage service). Thus it is only logical that I want to type the injected class with the interface, but this cannot be done the same way Angular 5 and lower does it.
So how can I type the injection into this global service with my interface?
I've tried
The Angular service typings describe an InjectableProvider, but this does not match any of the parameters of the siblings of InjectableProvider, so this gives a compiler (and tslint) error.
@Injectable({
providedIn: 'root'
}, {provide: IStorageService, useClass: SessionStorage})
export class MyService implements MyInterface {...}?useValuerequires a value (an actual instance of a class), anduseClassallows you to use classes. So try withuseClass, and maybeuseInterface(but this one I'm not sure)useClassdoes not work either, since it does not match the parameter of the InjectableProvider (updated answer). About 'why don't you use (..) implements (..)', I don't want to do that because that way I still have to set the exact type in the constructor and I want to avoid that if possible