javascript - 如何在 Typescript 中按名称调用具有不同签名的方法?

标签 javascript angular algorithm typescript angular-http

我正在尝试设置一个方法来调用我的后端并为我做一些通用的事情。

所以我得出这段代码:

myFct() {
    this[type](url, params, options).pipe(...)
}

get<T>(url: string, params: HttpParams, options: any): Observable<HttpEvent<T>> {
    return this._http.get<T>(url, options);
}

post<T>(url: string, params: HttpParams, options: any): Observable<HttpEvent<T>> {
    return this._http.post<T>(url, params, options);
}

put<T>(url: string, params: HttpParams, options: any): Observable<HttpEvent<T>> {
    return this._http.put<T>(url, params, options);
}

delete<T>(url: string, params: HttpParams, options: any): Observable<HttpEvent<T>> {
    return this._http.delete<T>(url, options);
}

但是我发现 4 方法是多余的,我想知道是否有直接这样做的方法:

this._http[type](url, params, options)

但是我得到这个错误:

Cannot invoke an expression whose type lacks a call signature

因为 GETDELETE 的签名中没有 HttpParams

它们是我可以根据条件返回参数的方法吗?还是返回两个参数和签名匹配?

最佳答案

您可以使用 .length property of a function 的事实返回它需要的参数数量,并执行:

(this._http[type].length === 3 ? 
    this._http[type](url, params, options) : 
    this._http[type](url, options));

关于javascript - 如何在 Typescript 中按名称调用具有不同签名的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068216/

相关文章:

javascript - 使用文件输入类型将图像发送到服务器

angular - 使用 Angular CLI 创建带有 Angular 4 Release 的项目

javascript - 无法使用 Angular $ http post将数据发布到实时服务器上的php,但在localhost上工作

algorithm - 如何从算法中看到碰撞?

algorithm - 了解上限、下限算法分析的实例

javascript - 使用 JavaScript 变量用 XML 数据动态填充标记

javascript - 双击时如何显示图钉?

angular - ng-bootstrap - ngbtooltip 不适用于 [(ngModel)]

arrays - 空间复杂度-涉及数组的各种情况函数

javascript - 使用动态导入时将 Webpack block url 作为字符串获取