我正在尝试在 angular + ts 中创建某种通用的 http 服务,我在其中提供模型类型并且它应该能够连接到相应的端点。
我有以下工作解决方案:
type Type<T> = new (...args: any[]) => T;
public getList<T>(c: Type<T>): Observable<T[]> {
const service = this.getService<T>(c);
return service.getList();
}
private getService<T>(c: Type<T>) {
const match = this.serviceMapping.find(i => c === i.type);
if (!match) {
throw new Error('No service registered for type ' + c.name);
}
return match.service;
}
我创建了映射对象来将提供的对象映射到服务
this.serviceMapping = [
{
type: Customer, // object class
service: customerService, // injected singleton instance of http service
},
]
和 getList 从组件调用,例如:
genericService.getList<Customer>(Customer).subscribe(...)
这工作正常并且服务返回结果,但我不喜欢我必须提供 Customer 类型作为方法参数。我想从方法参数中删除它,只为请求相关的数据(查询参数,正文,...)留下参数。
有什么可能吗?
我想这样使用它:
genericService.getList<Customer>().subscribe(res => this.customers = res);
genericService.getById<Customer>(customerId).subscribe(...)
genericService.create<Customer>(customerData).subscribe(...)
genericService.getList<Foo>(customerData).subscribe(res => this.foos = res;)
genericService.getList<Bar>(customerData).subscribe(res => this.bars = res)
(当然,我会确保每个服务都提供这些方法。这应该处理默认的 CRUD 操作)。
谢谢
答案 0 :(得分:0)
从 typescript 2.8 开始,这是可能的。您可以获取函数的返回类型。 参考这个合并的 PR - https://github.com/Microsoft/TypeScript/pull/21847
您可以创建一个通用方法,将函数作为参数传递并检查类型。