Angular 6 ProvidedIn-如何自定义@Injectable()提供程序以进行依赖项注入? [英] Angular 6 providedIn - how to customize the @Injectable() provider for dependency injection?
问题描述
在Angular 5中,如果我有AbstractClassService
和ExtendedClassService
扩展了抽象,则可以在NgModule的providers数组中做到这一点:
In Angular 5, if I had AbstractClassService
and ExtendedClassService
that extends the abstract, I could do this in my NgModule's providers array:
@NgModule({
providers: [
{provide: AbstractClassService, useClass: ExtendedClassService}
]
})
export class AppModule {}
这将使我可以轻松地将ExtendedClassService
与另一个进行测试.仍然可以使用Angular 6进行此操作,但是可以在服务本身中设置新的providedIn
选项以减小包的大小:
This would allow me to switch ExtendedClassService
with another for testing or whatever very easily. This can still be done with Angular 6, however there is the new providedIn
option that can be set within the service itself to reduce bundle size:
@Injectable({providedIn: 'root'})
export class ExtendedClassService extends AbstractClassService {}
在使用新的providedIn
时,我是否有办法完成与Angular 5相同的工作?像这样:
Is there a way for me to accomplish the same thing I had with Angular 5 while using the new providedIn
? Something like this:
@Injectable({providedIn: 'root', provide: AbstractClassService})
export class ExtendedClassService extends AbstractClassService {}
推荐答案
我需要做两件事.
首先,在创建继承类时使用implements
代替extends
,并且请勿在此处使用providedIn
键:
First, use implements
instead of extends
when creating the inheriting class and do not use the providedIn
key there:
@Injectable() // removed providedIn
export class ExtendedClassService implements AbstractClassService {}
第二,改为将提供程序说明添加到抽象类中:
Second, add the provider instructions to the abstract class instead:
@Injectable({providedIn: 'root', useClass: ExtendedClassService})
export abstract class AbstractClassService {}
也可以在其中使用其他提供程序配置(useValue
,useExisting
,useFactory
).
Other provider configuration (useValue
, useExisting
, useFactory
) can also be used there.
使用此评论这导致我
Credit goes to Abinesh with this comment which led me to the linked blog post. Many thanks to the blog author!
这篇关于Angular 6 ProvidedIn-如何自定义@Injectable()提供程序以进行依赖项注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!