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

前端 未结 1 1378
一向
一向 2020-12-08 22:43

In Angular 5, if I had AbstractClassService and ExtendedClassService that extends the abstract, I could do this in my NgModule\'s providers array:<

相关标签:
1条回答
  • 2020-12-08 23:29

    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!

    0 讨论(0)
提交回复
热议问题