2

With the new angular 2 DI we can do this:

import HeroService from './HeroService';

bootstrap(AppComponent, [provide(HeroService,{useClass:HeroService})]);

There is a way to code to an 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) {}

}
3

1 Answer 1

2

I'm not sure that such approach is possible since interfaces are erased at runtime in TypeScript and can be referenced.

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 a plunkr describing this: https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=preview.

This answer could also give you some additional hints: Interface based programming with TypeScript, Angular 2 & SystemJS.

Hope it helps you, Thierry

Sign up to request clarification or add additional context in comments.

1 Comment

It seems it can be done using tokens. See a working version in the next link plnkr.co/edit/A6ezGRUlrFsfLr4GjaGi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.