I\'m currently trying to clean up some code in order to program against interfaces rather than against implementations but can\'t figure out how to.
To be more speci
TypeScript doesn't produce any symbols for interfaces, but you're going to need a symbol of some sort to make dependency injection work.
Solution: use OpaqueTokens as your symbol, assign a class to that token via the provide() function, and use the Inject function with that token in the constructor of your class.
In the example here, I've assumed that you want to assign PostsServiceImpl to PostsService in the Posts component, because it's easier to explain when the code is all in the same place. The results of the provide() call could also be put into the second argument of angular.bootstrap(someComponent, arrayOfProviders), or the provide[] array of a component higher up the hierarchy than the Posts component.
In components/posts/posts.service.ts:
import {OpaqueToken} from "@angular/core";
export let PostsServiceToken = new OpaqueToken("PostsService");
In your constructor:
import {PostsService, PostsServiceImpl, PostsServiceToken} from 'components/posts/posts.service';
import {provide} from "@angular/core";
@Component({
selector: 'posts',
providers: [provide(PostsServiceToken, {useClass: PostsServiceImpl})]
})
export class Posts {
private postsServices: PostsService;
constructor(
@Inject(PostsServiceToken)
postsService: PostsService
) {
console.log('Loading the Posts component');
this.postsServices = postsService;
...
}
...
}