通过新的 Angular 2 DI,我们可以做到这一点:
import HeroService from './HeroService';
bootstrap(AppComponent, [provide(HeroService,{useClass:HeroService})]);
有一种方法可以对接口(interface)进行编码,这样我们就可以做到这一点吗?
// typescript does not compile interfaces to plain js, we can use this in the provide function?
interface SomeInterface { name: string }
class HeroService implements SomeInterface {}
bootstrap(AppComponent, [provide(SomeInterface,{ useClass: HeroService })]);
// component
class myComponent {
constructor(hero: SomeInterface) {}
}
最佳答案
我不确定这种方法是否可行,因为接口(interface)在 TypeScript 中运行时会被删除并且可以被引用。
如果您在服务中尝试此操作:
export interface SomeInterface {
someMethod();
}
export class HeroService implements SomeInterface {
(...)
}
当尝试从另一个模块导入它时,我们将遇到未定义的情况:
import {HeroService,SomeInterface} from './hello.service';
console.log('service = '+HeroService); // <---- not null
console.log('interdace = '+SomeInterface); // <---- undefined
这里有一个 plunkr 描述了这一点:https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=preview .
这个答案还可以给你一些额外的提示:Interface based programming with TypeScript, Angular 2 & SystemJS .
希望对你有帮助 蒂埃里
关于javascript - Angular 2 DI 编码到接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849729/