我正在用6.0.7构建一个应用程序,并尝试用新的:
@Injectable({
providedIn: 'root'
})但是,如何使用接口输入注入呢?
问题
我有两个服务,Authentication.service和SessionStorage.service.我想将会话存储注入身份验证服务。这可以通过以下方式实现:
constructor(private sessionStorage: SessionStorage) {
}那里没问题。但出于面向对象的目的,我希望在此服务之上有一个interface (这样我就可以将两个本地存储服务实现为会话存储服务)。因此,我想用接口键入注入的类是合乎逻辑的,但这不能以角5及以下是吗?的方式进行。
那么,如何使用我的接口在这个全局服务中键入注入呢?
我试过
角服务类型描述了一个InjectableProvider,但是这不匹配InjectableProvider兄弟类的任何参数,因此这会给编译器(和tslint)带来一个错误。
@Injectable({
providedIn: 'root'
}, {provide: IStorageService, useClass: SessionStorage})发布于 2018-08-22 10:13:06
这可以用InjectionToken来完成,它是对过时的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
) {}发布于 2018-07-10 09:47:54
我使用了下面这样的方法来解决这个问题
app.module.ts
providers: [
{ provide: AlmostInterface, useClass: environment.concrete }
...
]AlmostInterface.ts
export abstract class AlmostInterface {
abstract myMethod();
}MyConcrete.ts
export class MyConcrete implements AlmostInterface {
myMethod() { ... }; // implementation
}
export class MyConcreteAlternative implements AlmostInterface {
myMethod() { ... }; // implementation
}environment.ts
export const environment = {
production: false,
concrete: MyConcreteAlternative
};environment.prod.ts
export const environment = {
production: true,
concrete: MyConcrete
};发布于 2018-07-10 12:00:59
我认为不能使用类型记录接口进行依赖注入,因为类型记录接口在运行时不存在(仅用于编译时的类型安全性)。
我建议对其使用抽象类。
编辑:您似乎可以在@Injectable的first参数中使用,而不是像您的示例那样作为第二个。将此与@k0zakinio的回答相结合,结果是:
@Injectable({
providedIn: 'root',
useClass: environment.concrete,
deps: []
})
export abstract class SessionStorage { }您似乎还需要通过deps或inject声明您的依赖项,签出此github问题。我希望这次我的回答会有更多的帮助。
https://stackoverflow.com/questions/51174859
复制相似问题