首页 > 解决方案 > 如何将参数传递给不带括号的函数?

问题描述

我有以下代码:

this.somePromiseFn<T>  // this fn is actually a promise
.then(res => res as T)
.catch(err => this.handleError<T>(err));

handleError<T>(err: HttpErrorResponse) {
  // do something here
  // and return like
  return {} as T;
}

上面的代码工作正常。但是如何在不使用另一个回调函数的情况下将err参数直接传递给方法。handleError由于catch默认情况下将 传递err给回调函数,它也应该将 传递errhandleCatchError. 我想要类似的东西:

this.somePromiseFn<T>
.then(res => res as T)
.catch(this.handleCatchError<T>); // this line gives error 'An argument for 'err' was not provided'

但是上面的代码会产生错误说:

预期 1 个参数,但得到 0。
未提供“err”参数。

虽然我已经访问过以下问题:

  1. addEventListener 调用该函数,我什至没有要求它
  2. Javascript“addEventListener”事件在页面加载时触发

但上述问题也建议使用另一个回调函数。

标签: angulartypescript

解决方案


this.somePromiseFn<T>
.then(res => res as T)
.catch(this.handleCatchError<T>);

这应该可以,尝试重现错误,但可以查看演示,可能是我遗漏了一些东西,如有必要,请检查并更新。


推荐阅读