Angular 6 使用界面服务

我创建了一个应用程序 Angular /
6.0.7

/ 并尝试创建新服务:


@Injectable/{
providedIn: 'root'
}/


但是如何用界面进入喷射?

问题

我有 2 服务,

Authentication.service



SessionStorage.service

. 我想实施 sessionstorage 在身份验证服务中。 这可以用:


constructor/private sessionStorage: SessionStorage/ {
}


没问题。 但是对于面向对象的目的,我想拥有
interface

高于此服务 /这样我就可以作为服务实施 localstorage, 所以服务 sessionstorage/. 因此,我想用界面进入输入的类是非常合乎逻辑的,但它不能就像
https://coderoad.ru/40068456/
.

那么,我如何使用我的界面进入此全局服务中的注入?

我试过了

服务类型 Angular 描述
InjectableProvider

, 但它与兄弟姐妹的任何参数都不符合
InjectableProvider

, 因此,它给出了一个编译器错误 /和 tslint/.


@Injectable/{
providedIn: 'root'
}, {provide: IStorageService, useClass: SessionStorage}/
已邀请:

江南孤鹜

赞同来自:

这可以完成
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
/ {}

君笑尘

赞同来自:

我用了像下一个解决这个问题的东西

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
};

二哥

赞同来自:

我想你不能使用 typescript 引入依赖性的接口,从而提高

typescript 接口不存在

在执行期间 /只有在汇编期间就业安全/.

我建议使用这个

抽象类

.

EDIT:
看起来你可以使用
useClass



第一的

范围 @Injectable,, 而不是在第二个,如你榜样。 将此与答案相结合 @k0zakinio's 导致:


@Injectable/{
providedIn: 'root',
useClass: environment.concrete,
deps: []
}/
export abstract class SessionStorage { }


似乎您还需要宣布您的依赖项
deps

或者
inject

, 检查这一点
https://github.com/angular/angular/issues/23592
github . 我希望这次我的答案会有所帮助。

快网

赞同来自:

你可以使用类似的东西 -


[{ provide: InterfaceName, useClass: ClassName}]

要回复问题请先登录注册