Is it possible to inject interface with angular2?

No, interfaces are not supported for DI. With TypeScript interfaces are not available at runtime anymore, only statically and therefore can’t be used as DI tokens.

Alternatively you can use strings as keys or InjectionToken

provide('CoursesServiceInterface', {useClass: CoursesServiceMock}) // old

providers: [{provide: 'CoursesServiceInterface', useClass: CoursesServiceMock}]

and inject it like

constructor(@Inject('CoursesServiceInterface') private coursesService:CoursesServiceInterface) {}

See also https://angular.io/api/core/InjectionToken

Leave a Comment