Angular injector.get of abstract class

Viewed 18

In my angular project I've got many components: each one of the has a provider. The provider is a custom service which extends an abstract class. Each one of these components can open a dialog (opened with MatDialog), and I would like to get the component's provider with injector.get, but how can I do that with an abstract class? Example:

@Component({
  providers: [FirstClass] // this extends BaseClass
})
export class MyComponent{}

@Component({
  providers: [SecondClass] // this extends BaseClass
})
export class SecondComponent{}

From the dialog I would like to do something like this:

injector.get<BaseClass>(BaseClass)

But I noticed that this isn't possible, so is there another way to take their provider having that abstract class?

Thanks in advance.

1 Answers

in your case BaseClass token is used to inject an instance. thus you need to register something with this token

providers: [{
  provide: BaseClass,
  useClass: SecondClass
}]

or, you could make your class injectable by several tokens

providers: [
 SecondClass,
 {
   provide: BaseClass,
   useExisting: SecondClass
  }
]

in 2nd version you could inject Second class with both BaseClass and SecondClass token

Related