angular - 如何在 Typescript 中动态设置类的函数?
问题描述
我有一个带有函数a和b的基类blah。
我想扩展(或创建可能具有函数 a 或 b(或两者)的此类的实例),这样如果我创建BaseClassWithA
并尝试调用,instance.b()
我将收到编译错误。
具体来说,这是针对 Base CRUD Api 的,我将使用各种特定的 API 实例对其进行扩展,例如“UsersAPI”。让我们假设用户 API 可能只有“GET”作为允许的方法。所以如果我/另一个开发者去调用UsersAPI.delete
,他们会得到一个编译错误。
下面是 Base API 类的示例:
export class CRUDBaseAPI<T extends ApiBaseType> {
constructor(
protected apiConfig: ApiConfig,
protected http: HttpClient,
protected errorService: ErrorService,
protected allowedMethods: Method[] = ['get', 'update','delete'],
protected httpConfig?: HttpConfiguration,
) {
}
public get(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
return this.http.get<T>(`${this.apiConfig.url}/${entity.id}`, this.getFullHttpConfiguration(httpConfig)).toPromise()
.then(returnData)
.catch(this.handleError(`Unable to retrieve ${this.apiConfig.entityName} record.`));
}
public update(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
return this.http.post(`${this.apiConfig.url}/${entity.id}`, entity, this.getFullHttpConfiguration(httpConfig)).toPromise()
.then(returnData)
.catch(this.handleError(`Unable to update ${this.apiConfig.entityName} record.`));
}
public delete(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
// TODO open confirm modal here and delete only if user confirms
return this.http.delete(`${this.apiConfig.url}/${entity.id}`, this.getFullHttpConfiguration(httpConfig)).toPromise()
.then(returnData)
.catch(this.handleError(`Unable to delete ${this.apiConfig.entityName} record.`));
}
}
function returnData(httpResponse: any) {
return httpResponse;
}
解决方案
您可以在每个子类中保护 、 和 方法get
,update
然后使用仅调用超级方法的简单包装器覆盖您希望公开的方法。delete
CRUDBaseAPI
推荐阅读
- java - Android Studio、Java 和 SQLite 问题创建数据库
- php - 文件未上传到数据库
- python - 从 Python 中用 BeautifulSoup 创建的列表中获取整数
- c - 无法访问地址处的内存
- xml - MSDeploy - 在同一部署中转换配置两次
- java - 如何在不使用 Android 中的任何 3rd 方库的情况下从基于 json 的 api 获取 json 数据?
- r - R- 如何在不使用 ggmap 的情况下使用 ggplot 和 sf 获得具有州界的美国地图?
- javascript - javascript仅通过请求scrape / webcrawl登录到没有浏览器的网页
- java - Spring Autowire 返回 Null 除非窗口直接通过 init 方法加载
- bash - 命令未在 bash 脚本中找到