Ionic3更新后json()方法报错及代码问题排查
问题原因及解决方案
这个报错在Ionic3后期更新中挺常见的,核心和Angular HTTP模块的版本变化有关,我帮你拆解清楚:
为什么会报错?
Ionic3的最后几次更新里,官方逐步把旧的Http模块(来自@angular/http)替换成了更高效的HttpClient模块(来自@angular/common/http),两种模块的响应处理逻辑不一样:
- 如果你还在用旧的
Http,大概率是类型导入出错,或者更新后TypeScript的类型定义调整,导致它识别不了Response上的json()方法; - 要是你已经切换到
HttpClient,那问题更直接:HttpClient的get方法默认会自动解析JSON响应,返回的Observable直接就是解析好的数据对象,不再是Response实例,自然没有json()方法。
两种解决方案任选
方案1:继续用旧的Http模块(兼容现有代码)
如果不想大改代码,可以按这几步修复:
- 确保所有相关导入都来自
@angular/http:import { Http, Headers, Response } from '@angular/http'; - 在
app.module.ts里确认导入的是HttpModule而非HttpClientModule:import { HttpModule } from '@angular/http'; @NgModule({ imports: [ // ...其他模块 HttpModule ] }) - 在
map操作里显式指定Response类型,帮TypeScript明确识别:getCategorys(){ var headers = new Headers(); headers.append('Content-Type','application/x-www-form-urlencoded'); return this.http.get("http://localhost/Test1/getCity.php?action=getcategory",{headers: headers}) .map((res: Response) => res.json()); }
方案2:迁移到HttpClient模块(推荐,符合后续规范)
这是官方建议的方向,代码会更简洁:
- 替换导入:把旧的HTTP相关导入换成新的:
import { HttpClient, HttpHeaders } from '@angular/common/http'; - 更新模块配置:在
app.module.ts里用HttpClientModule替换HttpModule:import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ...其他模块 HttpClientModule ] }) - 修改Provider代码:
HttpHeaders是不可变对象,要用set方法添加头信息;- 删掉
.map(res => res.json()),因为HttpClient会自动解析JSON:getCategorys(){ let headers = new HttpHeaders().set('Content-Type','application/x-www-form-urlencoded'); return this.http.get("http://localhost/Test1/getCity.php?action=getcategory",{headers: headers}); }
要是你的后端返回的不是JSON格式,还能通过responseType参数指定类型(比如'text'),不过你的场景用默认的JSON就足够啦。
内容的提问来源于stack exchange,提问作者khaled jarrad
相关产品推荐
相关产品推荐

