我正在使用Angular(6.0.7)构建一个应用程序,我正在尝试使用new创建一个服务:
@H_301_36@解决方法
@Injectable({ providedIn: 'root' })
但是如何键入接口注入?
问题
我有2个服务,Authentication.service和SessionStorage.service.我想将sessionstorage注入到身份验证服务中.这可以通过以下方式完成:
constructor(private sessionStorage: SessionStorage) { }
没问题.但是出于面向对象的目的,我希望在此服务之上有一个接口(这样我就可以将localstorage服务实现为sessionstorage服务).因此,我想用接口键入注入的类是合乎逻辑的,但这不能以与Angular 5 and lower does it相同的方式完成.
那么如何使用我的界面在这个全局服务中输入注入?
我试过了
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 ) {}