问题
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