【问题标题】:Angular 5's HttpClient: What arguments does toPromise() accept?Angular 5 的 HttpClient:toPromise() 接受哪些参数?
【发布时间】:2018-04-24 19:00:35
【问题描述】:

如果我尝试像这样返回特定类型的承诺:

public myMethod(): Promise<MyType> {
  return this.httpClient.get('/my/url').toPromise();
}

...我收到返回类型 Promise 与预期类型 Promise 不匹配的错误。这很容易通过转换结果或这样做来解决:

public myMethod(): Promise<MyType> {
  return this.httpClient.get<MyType>('/my/url').toPromise();
}

不过,还有另一种选择,可以为 toPromise() 函数提供一个可选参数。我的 IDE 说参数的类型是“PromiseCtor: PromiseConstructorLike”或“PromiseCtor: typeof Promise”。

public myMethod(): Promise<MyType> {
  return this.httpClient.get('/my/url').toPromise(???);
}

我不知道什么语法可以满足 ???然而,在上面。

关于这里可以填写什么作为有效参数的任何想法?

【问题讨论】:

  • 我认为它要求Promise constructor。可以是原生的,也可以是你最喜欢的 Promise 库提供的。这对MyType 没有帮助,顺便说一句。
  • 假设您有一个特殊类型的 Promise MyPromise,您将传递该类型(即 MyPromise 的构造函数)。目标不是解决您遇到的问题。目标也是返回特定类型的 Promise。

标签: typescript promise httpclient angular5


【解决方案1】:

需要在get方法get&lt;MyType&gt;中指定类型:

public myMethod(): Promise<MyType> {
   return this.httpClient.get<MyType>('/my/url').toPromise();
}

【讨论】:

    【解决方案2】:
    public async myMethod(): MyType {
      return await <MyType>this.httpClient.get('/my/url').toPromise();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2014-08-31
      • 2010-12-06
      • 2014-09-25
      • 2019-02-28
      • 2017-09-04
      相关资源
      最近更新 更多