Angular 2 DI Coding for an Interface

With the new angular 2 DI we can do this:

import HeroService from './HeroService'; bootstrap(AppComponent, [provide(HeroService,{useClass:HeroService})]); 

Is there a way to code the interface so we can do this?

 // typescript does not compile interfaces to plain js, we can use this in the provide function? interface SomeInterface { name: string } class HeroService implements SomeInterface {} bootstrap(AppComponent, [provide(SomeInterface,{ useClass: HeroService })]); // component class myComponent { constructor(hero: SomeInterface) {} } 
+2
source share
1 answer

I'm not sure that this approach is possible, as interfaces are erased at runtime in TypeScript and can be specified.

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('interdace = '+SomeInterface); // <---- undefined 

Here is the plunkr description: https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=preview .

This answer can also give you some additional tips: Interface-based programming with TypeScript, Angular 2, and SystemJS .

Hope this helps you, Thierry

+2
source

Source: https://habr.com/ru/post/1015109/


All Articles