Export class as interface in Angular2

风格不统一 提交于 2019-12-17 17:22:28

问题


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.


回答1:


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() { ... }
}

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 }]
...


来源:https://stackoverflow.com/questions/43572149/export-class-as-interface-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!