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