我想知道 Angular2 中是否有正确的方法来注入接口? (参见下文)
我认为这与界面上缺少 @Injectable() 装饰器有关,但似乎这是不允许的。
Regards.
当 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; };
}