简体   繁体   中英

Angular 2 dependency injection: Host as parent class

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM