将类导出为 Angular2 中的接口 [英] Export class as interface in Angular2

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

问题描述

有没有办法将类导出为接口,然后将该接口导入到 Angular 2 的另一个模块中?我需要能够在某些组件的构造函数中注入类,例如应该注册为提供者.

Is there a way to export a class as interface and then import that interface in another module in Angular 2? I need to be able to inject the class in a constructor in some components e.g should be registered as provider.

推荐答案

为了同时用作接口和提供者令牌,它可能是抽象类.这就是它在 Angular 代码库中的实现方式.

In order to be used as both an interface and provider token, it may be abstract class. This is how it is done in Angular code base itself.

如果具体类有继承自抽象类的东西,后者可以是可扩展的:

If concrete class has something to inherit from abstract class, the latter can be extendable:

export abstract class Foo {
  abstract bar();

  baz() { ... }
}

export class ConcreteFoo extends Foo {
  bar() { ... }
}

...
provider: [{ provide: Foo, useClass: ConcreteFoo }]
...

否则使抽象类不可扩展和不可实例化更安全:

Otherwise it's safer to make abstract class non-extendable and non-instantiatable:

export abstract class Foo {
  private constructor() {
    throw new Error('should not be instantiated directly');
  }

  abstract bar();
}

export class ConcreteFoo implements Foo {
  bar() { ... }
}

需要注意的是,任何类都可以用作 TypeScript 中的接口.所以如果真的不需要区分接口和实现,它可能只是一个具体的类:

It should be noticed that any class can be used as an interface in TypeScript. So if there's no real need to differentiate between interface and implementation, it may be just one concrete class:

export class Foo {
  bar() { ... }

  baz() { ... }
}

...
provider: [Foo]
...

如有必要,稍后可以用作接口:

Which may be used later as an interface if necessary:

export class SomeFoo implements Foo { ... }

...
provider: [{ provide: Foo, useClass: SomeFoo }]
...

这篇关于将类导出为 Angular2 中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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