Angular 6 providedIn - how to customize the @Injectable() provider for dependency injection?

↘锁芯ラ 提交于 2019-12-28 12:11:54

问题


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

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

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

回答1:


I needed to do two things.

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

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!



来源:https://stackoverflow.com/questions/50489412/angular-6-providedin-how-to-customize-the-injectable-provider-for-dependenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!