gpt4 book ai didi

javascript - Angular 2 DI编码到接口(interface)

转载 作者:行者123 更新时间:2023-11-29 21:36:06 25 4
gpt4 key购买 nike

使用新的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com