Angular 6 providedIn - 如何自定义 @Injectable() 提供程序以进行依赖注入? [英] Angular 6 providedIn - how to customize the @Injectable() provider for dependency injection?

查看:19
本文介绍了Angular 6 providedIn - 如何自定义 @Injectable() 提供程序以进行依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 5 中,如果我有扩展抽象的 AbstractClassServiceExtendedClassService,我可以在我的 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 {}

其他提供者配置(useValueuseExistinguseFactory)也可以在那里使用.

Other provider configuration (useValue, useExisting, useFactory) can also be used there.

感谢 Abinesh 与此评论这导致我 链接的博客文章.非常感谢博客作者!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆