Mr.*_*guy 8 service dependency-injection typescript angular angular6
我正在使用Angular(6.0.7)构建应用程序,并且尝试使用新的创建服务:
@Injectable({
providedIn: 'root'
})
Run Code Online (Sandbox Code Playgroud)
但是,如何使用接口键入注入?
问题
我有2个服务,Authentication.service和SessionStorage.service。我想将sessionstorage注入到身份验证服务中。可以通过以下方式完成:
constructor(private sessionStorage: SessionStorage) {
}
Run Code Online (Sandbox Code Playgroud)
没问题。但是出于面向对象的目的,我希望interface在此服务之上(这样我就可以将localstorage服务都实现为sessionstorage服务)。因此,我想用接口键入注入的类是合乎逻辑的,但这不能以与Angular 5及更低版本相同的方式完成。
那么,如何通过界面在该全局服务中键入注入?
我试过了
Angular服务类型描述了InjectableProvider,但是与的兄弟姐妹的任何参数都不匹配InjectableProvider,因此这会产生编译器(和tslint)错误。
@Injectable({
providedIn: 'root'
}, {provide: IStorageService, useClass: SessionStorage})
Run Code Online (Sandbox Code Playgroud)
我用类似下面的东西来解决这个问题
app.module.ts
providers: [
{ provide: AlmostInterface, useClass: environment.concrete }
...
]
Run Code Online (Sandbox Code Playgroud)
几乎接口.ts
export abstract class AlmostInterface {
abstract myMethod();
}
Run Code Online (Sandbox Code Playgroud)
MyConcrete.ts
export class MyConcrete implements AlmostInterface {
myMethod() { ... }; // implementation
}
export class MyConcreteAlternative implements AlmostInterface {
myMethod() { ... }; // implementation
}
Run Code Online (Sandbox Code Playgroud)
环境.ts
export const environment = {
production: false,
concrete: MyConcreteAlternative
};
Run Code Online (Sandbox Code Playgroud)
环境.prod.ts
export const environment = {
production: true,
concrete: MyConcrete
};
Run Code Online (Sandbox Code Playgroud)
可以使用来完成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
) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14810 次 |
| 最近记录: |