我想知道在Angular2中是否有正确的方法来注入接口? (参见下面)是否可以使用angular2注入接口?
我认为这与接口上缺少的@Injectable()装饰器有关,但似乎这是不允许的。
问候。
当CoursesServiceInterface被作为接口来实现,打字稿编译器抱怨 “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; };
}
useClass:是我失踪了......太糟糕了,是不是在官方教程 – Aligned
https://angular.io/docs/ts/最新版本/ cookbook/dependency-injection.html#!#usevalue –