我想知道在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令牌.
原文链接:https://www.f2er.com/angularjs/140822.html或者,您可以使用字符串作为键或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