【问题标题】:How to pass argument to the function without parentheses?如何将参数传递给不带括号的函数?
【发布时间】:2019-05-20 19:58:52
【问题描述】:

我有以下代码:

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 传递给回调函数,它也应该将err 传递给handleCatchError。我想要类似的东西:

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 calls the function without me even asking it to
  2. Javascript "addEventListener" Event Fires on Page Load

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

【问题讨论】:

  • 这似乎不是 minimal reproducible example,除非您在对其中一个答案的评论中计算 stackblitz 链接。 this.someFn().then((r) =&gt; console.log(r)).catch(this.cb); 对你有用吗?如果不是,请编辑此问题以构成可重现的问题。祝你好运!

标签: angular typescript


【解决方案1】:
this.somePromiseFn<T>
.then(res => res as T)
.catch(this.handleCatchError<T>);

这应该可以,尝试重现错误但它可以工作see a demo,可能是我遗漏了一些东西,如有必要,请检查并更新。

【讨论】:

  • 您的代码正在运行,因为您的代码中没有类型变量。见here,它不工作..!
【解决方案2】:

基于你提供的stackblitz,见

this.someFn().then(r => console.log(r)).catch(err => this.cb<any>(err));

【讨论】:

  • 感谢您的回答,但我已经在使用您提供的解决方案了..!但我想要另一种(分类)方式..!
【解决方案3】:

不要给出生成的类型并绑定“this”:

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

【讨论】:

  • 感谢您的回答,但类型变量是必需的..!
  • 如果不调用handleCatchError&lt;T&gt;()函数,就不能给出泛型类型。
猜你喜欢
  • 2020-09-12
  • 2011-11-02
  • 1970-01-01
  • 2013-06-15
  • 2012-05-12
  • 1970-01-01
  • 2020-03-05
  • 2013-05-21
  • 1970-01-01
相关资源
最近更新 更多