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

查看:80
本文介绍了在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天全站免登陆