Angular 2 DI 编码到接口 [英] Angular 2 DI coding to an interface

查看:22
本文介绍了Angular 2 DI 编码到接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的 angular 2 DI,我们可以做到这一点:

With the new angular 2 DI we can do this:

import HeroService from './HeroService';

bootstrap(AppComponent, [provide(HeroService,{useClass:HeroService})]);

有没有办法对接口进行编码,这样我们就可以做到这一点?

There is a way to code to an interface so we can do this?

// 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) {}

}

推荐答案

我不确定这种方法是否可行,因为接口在 TypeScript 中在运行时被擦除并且可以被引用.

I'm not sure that such approach is possible since interfaces are erased at runtime in TypeScript and can be referenced.

如果您在服务中尝试此操作:

If you try this in your service:

export interface SomeInterface {
  someMethod();
}

export class HeroService implements SomeInterface {
  (...)
}

当我们尝试从另一个模块导入它时,我们会得到 undefined:

We will have undefined when trying to import it from another module:

import {HeroService,SomeInterface} from './hello.service';

console.log('service = '+HeroService); // <---- not null
console.log('interdace = '+SomeInterface); // <---- undefined

这是一个 plunkr 描述:https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=预览.

Here is a plunkr describing this: https://plnkr.co/edit/RT59B0tw40lnq85XMMi7?p=preview.

这个答案也可以给你一些额外的提示:基于接口的编程使用 TypeScript、Angular 2 &SystemJS.

This answer could also give you some additional hints: Interface based programming with TypeScript, Angular 2 & SystemJS.

希望对你有帮助蒂埃里

这篇关于Angular 2 DI 编码到接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆