是否可以注入与angular2的界面?

我想知道在Angular2中注入接口是否有正确的方法? (参见下文)

我认为这与接口上缺少的@Injectable()装饰器有关,但似乎这是不允许的.

问候.

当CoursesServiceInterface实现为接口时,TypeScript编译器会抱怨“CoursesServiceInterface找不到名称”:

import {CoursesServiceInterface} from './CoursesService.interface';
import {CoursesService} from './CoursesService.service';
import {CoursesServiceMock} from './CoursesServiceMock.service';
bootstrap(AppComponent,[
  ROUTER_PROVIDERS,GlobalService,provide(CoursesServiceInterface,{ useClass: CoursesServiceMock })
  ]);

但以CoursesServiceInterface为界面:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
//@Injectable()
export interface CoursesServiceInterface {
    getAllCourses(): Promise<Course[]>;//{ return null; };
    getCourse(id: number): Promise<Course>;// { return null; };
    remove(id: number): Promise<{}>;// { return null; };
}

当服务是一个类时,TypeScript编译器不再抱怨:

import {Injectable} from 'angular2/core';
import {Course} from './Course.class';
@Injectable()
export class CoursesServiceInterface {  
    getAllCourses() : Promise<Course[]> { return null; };
    getCourse(id: number) :Promise<Course> { return null; };
    remove (id: number) : Promise<{}> { return null; };
}
否,DI不支持接口.使用TypeScript接口在运行时不再可用,只能静态地使用,因此不能用作DI令牌.

或者,您可以使用字符串作为键或Opaquetoken

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

并注入它

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

参见https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...