【问题标题】:Ionic5 & Typescript - propper http request : Convert fetch Promise to Observeable?Ionic 5 和 Typescript - 正确的 http 请求:将 fetch Promise 转换为 Observable?
【发布时间】:2020-09-24 05:55:27
【问题描述】:

我正在将我的 Ionic3 应用程序移植到 Ionic5 中,并且目前正在添加我的 http 请求。 在 Ionic3 中,我使用了 angular/http,但似乎是 deprecated。 这是我的带有 observables 的代码:

   this._http.get(requestURL)
      .map((result: Response) => {
        return this.run(result.json())
   });

现在,我如何使用 Ionic5 完成与 http 相同的实现?

Rx.Observable.fromPromise(fetch(url));

? 以上似乎不起作用。 fromPromise does not exist on Rx.Observeable.

【问题讨论】:

  • 你使用的是什么 RxJS 版本?
  • 刚刚检查 - 6.5.1

标签: typescript ionic-framework rxjs ionic5


【解决方案1】:

如果您使用的是 RxJS 6,则应使用 from 运算符,这会将 promise 转换为 observable

const request = fetch(url);

from(request).pipe(
  switchMap(response => response.json()),
 ... carry out other operations here.
)

【讨论】:

  • _http 来自哪里?
  • @ElDude 对不起,我复制错了。它应该是 fetch
  • 谢谢!我刚刚发现我必须用forEach 替换现在已经消失的map 函数。
  • 如何将响应转换为对象?如上所示,我曾经有result.json()。但它现在对我来说似乎失败了。我不确定如何处理Response 类型。
  • @ElDude 很抱歉回复晚了。我已更新我的答案以在 rxjs 管道中返回 response.json()
猜你喜欢
  • 1970-01-01
  • 2021-03-31
  • 2017-01-12
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
  • 2016-12-25
  • 2018-02-19
相关资源
最近更新 更多