我正在尝试创建一个通用的 DeleteableConfirmationComponent
,它将允许我显示确认对话框并从任何实现 Deleteable 的注入(inject)服务调用
界面。delete
方法
为此,我创建了这个接口(interface):
export interface Deleteable {
delete(object);
}
我有一个实现它的服务:
@Injectable()
export class LocalityService implements Deleteable {
delete(locality): Observable<Locality> {
// Delete logic.
}
}
对于 DeleteableConfirmationComponent
,我尝试使用构造函数注入(inject)服务:
export class DeleteableConfirmationComponent {
constructor(
public dialog: MdDialogRef<DeleteableConfirmationComponent>,
@Inject(MD_DIALOG_DATA) public data: any,
private service: Deleteable
) {}
delete() {
this.service.delete(this.object)
.subscribe(() => {
this.dialog.close();
});
}
}
但不幸的是,我收到一条错误消息,提示无法解析 DeleteableConfirmationComponent 的所有参数。
现在,我正在使用对话框数据选项,以便传递我的服务:
confirmDelete(locality) {
this.dialog.open(DeleteableConfirmationComponent, {
data: {
service: this.localityService
}
});
}
但它感觉很脏,并且允许注入(inject)任何类型的服务,而我想强制实现 Deleteable
接口(interface)的服务。
我在想我可能会更好地使用抽象类
,但我更喜欢组合而不是继承。
任何想法或最佳实践建议?
最佳答案
如评论中所述,您可以将接口(interface)转换为抽象类:
export abstract class Deleteable {
abstract delete(object);
}
然后在你的提供者中你可以将它映射到真实的类:
providers: [{ provide: Deleteable, useValue: new LocalityService() }]
您可能不喜欢这种方法,因为现在 LocalityService
似乎必须扩展 Deleteable
。但是,如果 LocalityService
需要扩展其他类怎么办?不允许多重继承:
// Error: Classes can only extend a single class
export class LocalityService extends OtherClass, Deleteable { }
或者您可能只是不喜欢 Deleteable
现在将出现在 LocalityService
的原型(prototype)链中:
export class LocalityService extends Deleteable {
delete(locality): void {
// Returns true
alert(this instanceof Deleteable);
}
}
然而,如图this answer , TypeScript 允许你像对待接口(interface)一样对待类。因此,您可以将 implements
与抽象类一起使用。
export class LocalityService extends OtherClass implements Deleteable {
delete(locality): void {
// Returns false
alert(this instanceof Deleteable);
}
}
因此,无论出于何种意图和目的,您的抽象类现在的行为都像一个接口(interface)。它甚至不会出现在原型(prototype)链中。
关于angular - 使用 Angular 4 注入(inject)接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45117934/