首页 > 解决方案 > Ionic 4 & RxJS 6:Ionic-native HTTP get 方法不从服务器返回数据

问题描述

我正在从 angular HttpClientModule 迁移到ionic-native HTTP,因为使用标准 HttpClient Module 访问第三方 API 是不可能的。我想让应用程序的测试尽可能简单:这意味着,当我在我的计算机上为应用程序添加功能时,我可以使用HttpClient; 当我在真实设备中进行测试时,我也可以通过迁移ionic-native HTTP和更改几行代码来做到这一点。

HttpClient我在我的电脑上测试它时,它在我的应用程序中工作得非常好。

service写在 HttpClient 模块中:

  getCaiyunForecast(): Observable<any> {
    return this.http.get(this.forecastUrl)
      .pipe(map((res: any) => { return res; }), catchError(this.processHttpmsg.handleError))
  }

service写在ionic-native HTTP

  getCaiyunForecast(): Observable<any> {
    return of(this._http.get(this.forecastUrl, {}, {})
      .then(res => { return JSON.parse(res.data) }, res => console.log(res.data)));
  }

当我订阅我的服务时HomePage

this.caiyunForecastService.getCaiyunForecast()
  .subscribe(res => {
    for (let i = 0; i < 3; i += 1) {
      let value = this.convertService.convertSkycon(res.result.hourly.skycon[i].value)
      this.hourlyWeather.push({
        temperature: res.result.hourly.temperature[i].value.toFixed(0),
        skycon: value,
        precipitation: res.result.hourly.precipitation[i].value.toFixed(1),
        wind: {
          speed: res.result.hourly.wind[i].speed,
          direction: res.result.hourly.wind[i].direction
        },
        cloudrate: res.result.hourly.cloudrate[i].value
      });
    }
  })

当我在我的服务(console.log(res.data))中执行 console.log 时,没有输出任何值。并且“无法读取每小时的属性未定义”错误;因此,我怀疑服务器没有返回任何数据。

是不是我做错了什么?我该如何更改它以使其正常工作?

标签: angularrxjsionic4ionic-native

解决方案


of不用于将 promise 转换为 observable。用于fromrxjs 6 和fromPromiserxjs 5.x

import { from } from 'rxjs';

和功能

getCaiyunForecast(): Observable<any> {
    return from(this._http.get(this.forecastUrl, {}, {})
      .then(res => { return JSON.parse(res.data) }, res => console.log(res.data)));
}

推荐阅读