1

I have a quick question: Can i bind Interface or abstract class (or just a parent class atleast) as @Host() of component? Seems like DI system can't resolve polymorphism.

I have interface like:

export interface Component {
}

and child component from this interface:

...
export class SomeComponent implements Component {
...
}

Now i want to create Directive, and use Component as host even when i put this directive on SomeComponent.

like:

constructor(private host: Component) { }
Maksim Fomin
  • 1,227
  • 2
  • 10
  • 8

1 Answers1

2

In fact, there is nothing at runtime corresponding TypeScript interfaces. This means that you can't use them as types.

If you try this in your service:

export interface SomeInterface {
  someMethod();
}

export class HeroService implements SomeInterface {
  (...)
}

We will have undefined when trying to import it from another module:

import {HeroService,SomeInterface} from './hello.service';

console.log('service = '+HeroService); // <---- not null
console.log('interface = '+SomeInterface); // <---- undefined

Here is a plunkr describing this: https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=preview.

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • What's about classes? Or abstract classes? Will this work? Typescript handbook: As we said in the previous section, a class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces. @Thierry – Maksim Fomin Jan 27 '16 at 06:44
  • Yes, agreed! For classes, it's a bit different. You have concrete things in the transpiled code. In Angular2, dependency injection is based on providers. This means that you can override providers for a token. You probably used this: `provide(LocationStrategy, {useClass: HashLocationStrategy})`. In this case, the class `HashLocationStrategy` when you ask for `LocationStrategy` to be injected. – Thierry Templier Jan 27 '16 at 09:31
  • This can be combined to hierarchical injection. I mean you can override this for a particular component (with its `providers` attribute) and other parent injectors. This answer could give you more hints about hierarchical injection: http://stackoverflow.com/questions/34804298/whats-the-best-way-to-inject-one-service-into-another-in-angular-2-beta/34807397. I hope it answers your question ;-) – Thierry Templier Jan 27 '16 at 09:31