带界面的Angular 6服务 [英] Angular 6 service with interface
问题描述
我正在使用Angular(6.0.7
)构建应用程序,并且尝试使用新的创建服务:
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?
问题
我有2个服务,分别为 Authentication.service 和 SessionStorage.service .我想将sessionstorage注入到身份验证服务中.可以通过以下方式完成:
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) {
}
没问题.但是出于面向对象的目的,我想在该服务之上使用interface
(这样我就可以将localstorage服务都实现为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?
我已经尝试
Angular服务类型描述了InjectableProvider
,但这与InjectableProvider
的兄弟姐妹的任何参数都不匹配,因此这会产生编译器(和tslint)错误.
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})
推荐答案
这可以通过InjectionToken
完成,它替代了过时的OpaqueToken
This can be done with InjectionToken
, which is a replacement for the obsolete OpaqueToken
export const AuthenticationProvider = new InjectionToken(
"AuthenticationProvider",
{ providedIn: "root", factory: () => new CognitoAuthenticationProvider() }
);
...
@Injectable()
export class CognitoAuthenticationProvider implements IAuthenticationProvider {
...
@Injectable({
providedIn: "root"
})
export class AuthenticationService {
constructor(
@Inject(AuthenticationProvider)
private authenticationProvider: IAuthenticationProvider,
private http: HttpClient
) {}
这篇关于带界面的Angular 6服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!