angular - Ionic 4 & RxJS 6:Ionic-native HTTP get 方法不从服务器返回数据
问题描述
我正在从 angular HttpClient
Module 迁移到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 时,没有输出任何值。并且“无法读取每小时的属性未定义”错误;因此,我怀疑服务器没有返回任何数据。
是不是我做错了什么?我该如何更改它以使其正常工作?
解决方案
of
不用于将 promise 转换为 observable。用于from
rxjs 6 和fromPromise
rxjs 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)));
}
推荐阅读
- javascript - 数据表不适用于使用 MVC 动态创建的表
- css - 使用css在矩形右侧创建动态三角形大小
- c# - 应用停止调试后 Xamarin Forms PCLStorage 文件丢失
- batch-file - 批量替换(重命名)部分文件名
- python - 有没有办法改变日志文件中运行的关键字的颜色,即使该关键字成功?
- wordpress - 按祖先页面过滤结果 wordpress
- python - 在 Anaconda 提示符下延迟 Python 脚本的执行?
- git - .gitignore 不排除任何文件和文件夹
- azure-active-directory - Azure AD 中基于组的许可 - 获取直接许可和继承许可 AzureAD 模块
- python - 使用python json模块的JSON解码器错误