【发布时间】:2017-12-20 10:31:11
【问题描述】:
我正在尝试创建一个通用的DeleteableConfirmationComponent,它允许我显示一个确认对话框并从任何实现Deleteable 接口的注入服务调用delete 方法。
为此,我创建了这个接口:
export interface Deleteable {
delete(object);
}
我有一个实现它的服务:
@Injectable()
export class LocalityService implements Deleteable {
delete(locality): Observable<Locality> {
// Delete logic.
}
}
对于DeleteableConfirmationComponent,我尝试使用构造函数注入服务:
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
}
});
}
但它感觉很脏,并且确实允许注入任何类型的服务,而我想强制实现 Deleteable 接口的服务。
我想我可能会更好地使用 abstract class,但我更喜欢组合而不是继承。
有什么想法或最佳实践建议吗?
【问题讨论】:
-
Unfortunately, you cannot use a TypeScript interface as a tokenangular.io/guide/… -
抽象类是这里的最佳选择
-
抽象类的使用与组合与继承无关。类也可以用作接口。不一定要延长。
标签: angular typescript generics interface